How can a weakly retained block cause a retain cycle when capturing “self”

前端 未结 1 593
夕颜
夕颜 2021-01-07 11:04

I have a class with a property which is a weak reference to a block.

@interface BlockTest : NSObject
    @property (nonatomic, weak) void(^testBlock)();
@end         


        
相关标签:
1条回答
  • 2021-01-07 11:27

    Blocks strongly capture objects within them regardless of how the block itself is referenced. The retain cycle warning is just that, a warning of the possibility. If you know based on the context of your app that this use will not cause a retain cycle you can safely ignore it. To get rid of the warning, you can pass self through an intermediary, strong or weak, as follows:

    __weak typeof(self) weakSelf = self;
    self.testBlock = ^{
        [weakSelf doSomething];
    };
    

    I'd change your block property to be a strong reference and do the above.

    0 讨论(0)
提交回复
热议问题