在Objective-C中,__typeof(&*self)是什么意思?它与__typeof(self)有何不同?

5

我在查看一些MVVM样例代码时遇到了这行代码:

__weak __typeof(&*self) weakSelf = self;
/*later used in some block*/

我了解__weaktypeof(self)的作用。为什么不直接使用__weak __typeof(self)或者__weak ViewController *weakSelf?参考和星号(&*self)有什么用?


指针在Objective-C中的工作方式与标准C相同。因此,&*selfself相同,并且在这种情况下,__typeof(self)按预期工作。 - Remy Lebeau
@RemyLebeau 是的,我看到它可以工作,只是想知道 &* 是干什么用的,感谢您的回答!就像 *self 解引用了 self 指针一样,& 是它的引用?我很困惑。 - denysowova
1
“就像*self解引用self指针,&是它的引用一样?” - 对的。* self 解引用 self 指针以获取对象,然后获取对象的地址,这与self指向的地址相同。” - Remy Lebeau
@RemyLebeau,现在我完全明白为什么&*selfself是同一件事了。非常感谢你! - denysowova
1
没有区别。然而,早期的LLVM不接受__typeof(self),因此这些ARC用户使用__typeof(&*self)来解决编译问题。 - DawnSong
2个回答

2

*&是C++的特点。它用于传递引用指针参数。

&*看起来像是某人非常困惑,最终编写了有效地没有操作的代码。但是,如果这是Objective-C++代码,那么&*可能会做一些事情(我记得智能指针可能需要奇怪的间接使用方式来完成某些操作)。

我参与的大多数项目都使用__weak typeof(self) weakSelf = self;


1
__weak __typeof(&*self)weakSelf = self;

__weak HomeVC *weakSelf2 = self;

NSLog(@"%@", weakSelf);  // This gives you the reference of the View Controller Object
NSLog(@"%p", weakSelf);  // This gives you only the address of the View Controller Object
NSLog(@"%@", weakSelf2); // Same as 1
NSLog(@"%p", weakSelf2); // Same as 2
NSLog(@"%@", &*self);    // Same as 1
NSLog(@"%p", &*self);    // Same as 2

// In the above logs you can notice the difference just by changing the format specifier. Hope this helps.

2
这并没有回答问题,只是指出了%p和%@之间的区别,这与问题无关。 - bbum

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接