![](/img/trans.png)
[英]“__weak typeof(self) weakSelf = self;” expected ; at end of declaration
[英]What exactly does '__weak typeof(self)weakSelf = self;' mean
这用于Objective-C的弱化模式
我的猜测是它意味着:为自己分配一个名为'weakSelf'的自我弱引用和自我类型(例如MyViewController)
如果它是正确的并且看起来很明显:我希望绝对确保做到这一点。 谢谢。
我的猜测是,它的意思是:指定一个弱引用自名为
weakSelf
和typeof
自(例如MyViewController
)
是的,这几乎就是它的含义。 self
的类型是MyViewController*
(带星号)而不是MyViewController
。
使用这种语法而不是简单地写的背后的想法
MyViewController __weak *weakSelf = self;
使重构更容易。 使用typeof
还可以定义可以粘贴到代码中任何位置的代码段。
使用来自libExtObjC的 @weakify
和@strongify
有助于简化有时在块周围必须做的“弱强舞”。 OP引用了这篇文章 。
例!
__weak __typeof(self) weakSelf = self;
__weak __typeof(delegate) weakDelegate = delegate;
__weak __typeof(field) weakField = field;
__weak __typeof(viewController) weakViewController = viewController;
[viewController respondToSelector:@selector(buttonPressed:) usingBlock:^(id receiver){
__strong __typeof(weakSelf) strongSelf = weakSelf;
__strong __typeof(weakDelegate) strongDelegate = weakDelegate;
__strong __typeof(weakField) strongField = weakField;
__strong __typeof(weakViewController) strongViewController = weakViewController;
与...
@weakify(self, delegate, field, viewController);
[viewController respondToSelector:@selector(buttonPressed:) usingBlock:^(id receiver){
@strongify(self, delegate, field, viewController);
你的解释是正确的。 但是,我发现当它以这种方式编写时,读起来有点令人困惑。 我更喜欢在typeof(self)
后增加一个空格:
__weak typeof(self) weakSelf = self;
根据您的编译器设置,您可能会收到警告“预期”;' 表达后“。 您可以通过将其更改为使用__typeof来解决此问题: __typeof(self) __weak weakSelf = self;
感谢Leo Natan和这个问题: https : //stackoverflow.com/a/32145709/1758224 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.