美文网首页
iOS block的循环引用

iOS block的循环引用

作者: ream_1489 | 来源:发表于2019-08-09 13:57 被阅读0次
__weak typeof(self) weakSelf = self;
self.blk = ^{
        __strong typeof(self) strongSelf = weakSelf;
        NSLog(@"Use Property:%@", strongSelf.name);
        //……
};
self.blk();

改为传参

self.blk = ^(UIViewController *vc) {
        NSLog(@"Use Property:%@", vc.name);
};
self.blk(self);

优点:

简化了两行代码,更优雅
更明确的API设计:告诉API使用者,该方法的Block直接使用传进来的参数对象,不会造成循环引用,不用调用者再使用weak避免循环

宏定义

#define WeakObj(o) autoreleasepool{} __weak typeof(o) o##Weak = o;
#define StrongObj(o) autoreleasepool{} __strong typeof(o) o = o##Weak;
@WeakObj(self);
[var setBlock:^{
    @StrongObj(self);
    [self doSomething];
}];

相关文章

网友评论

      本文标题:iOS block的循环引用

      本文链接:https://www.haomeiwen.com/subject/jigcjctx.html