我在查看一些MVVM样例代码时遇到了这行代码:
__weak __typeof(&*self) weakSelf = self;
/*later used in some block*/
我了解__weak
和typeof(self)
的作用。为什么不直接使用__weak __typeof(self)
或者__weak ViewController *weakSelf
?参考和星号(&*self
)有什么用?
我在查看一些MVVM样例代码时遇到了这行代码:
__weak __typeof(&*self) weakSelf = self;
/*later used in some block*/
我了解__weak
和typeof(self)
的作用。为什么不直接使用__weak __typeof(self)
或者__weak ViewController *weakSelf
?参考和星号(&*self
)有什么用?
*&
是C++的特点。它用于传递引用指针参数。
&*
看起来像是某人非常困惑,最终编写了有效地没有操作的代码。但是,如果这是Objective-C++代码,那么&*
可能会做一些事情(我记得智能指针可能需要奇怪的间接使用方式来完成某些操作)。
我参与的大多数项目都使用__weak typeof(self) weakSelf = self;
。
__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.
&*self
与self
相同,并且在这种情况下,__typeof(self)
按预期工作。 - Remy Lebeau* self
解引用self
指针以获取对象,然后&
获取对象的地址,这与self
指向的地址相同。” - Remy Lebeau&*self
和self
是同一件事了。非常感谢你! - denysowova__typeof(self)
,因此这些ARC用户使用__typeof(&*self)
来解决编译问题。 - DawnSong