在Objective-C块中使用typeof(self)来声明一个强引用

在Objective-C块中使用typeof(self)来声明一个强引用,第1张

概述使用weakSelf / strongSelf模式来避免在块中创建保留周期,此代码非常常见: typeof(self) __weak weakSelf = self;void (^block)() = ^{ typeof(weakSelf) strongSelf = weakSelf; // ...more code...}; 问题是,将第二种类型(weakSelf)更改为ty 使用weakSelf / strongSelf模式来避免在块中创建保留周期,此代码非常常见:
typeof(self) __weak weakSelf = self;voID (^block)() = ^{    typeof(weakSelf) strongSelf = weakSelf;    // ...more code...};

问题是,将第二种类型(weakSelf)更改为typeof(self)会导致在块中捕获self吗?

例如:

typeof(self) __weak weakSelf = self;voID (^block)() = ^{    typeof(self) strongSelf = weakSelf; // does using typeof(self) here end up capturing self?    // ...more code...};

如果没有捕获自我,是否有任何理由偏爱这种或那种方式?

解决方法 它没有. Ken所说的关于typeof是一个编译时表达式确实适用.

这里还有一段代码证明了这一点:

#import <Foundation/Foundation.h>int main(int argc,char *argv[]) {  @autoreleasepool {    NSObject *o = [NSObject new];    __weak typeof(o) weakO = o;    voID(^b)() = ^{      __strong typeof(o) strongO = weakO;      NSLog(@"o: %@",strongO);    };    o = nil;    b();    /* outputs:      2015-05-15 16:52:09.225 UnTitled[28092:2051417] o: (null)     */  }}
总结

以上是内存溢出为你收集整理的在Objective-C块中使用typeof(self)来声明一个强引用全部内容,希望文章能够帮你解决在Objective-C块中使用typeof(self)来声明一个强引用所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1242278.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存