How to avoid “Capturing ‘self’ strongly in this block is likely to lead to a retain cycle”

I was trying to update a UILabel from inside a block the other day, and was puzzled by the above Xcode warning: “Capturing ‘self’ strongly in this block is likely to lead to a retain cycle”. The full code looked like this:

self.mainController.controllerPausedHandler = ^(GCController *controller){

        // triggers a warning
        [self displayMessage:@"Pause Button"];

    };

As it turns out, the trouble was that a block executed in self cannot capture a reference to itself (self) without there being a never ending loop involved. It’s probably to complicated for me to understand and/or care about, but thankfully there’s a relatively easy way to correct this problem.

All we need to do is to create a weak reference to self and use it in our block instead. Method calls and property access will still work, but the strong retain cycle no longer exists, making the compiler happy. And that is, after all, the most important thing in the world: to make some frigging software happy.

Here’s the amended version, using a typeof weakSelf. It can be used just like self inside the block:

    // we need a weak self here for in-block access
    __weak typeof(self) weakSelf = self;

    self.mainController.controllerPausedHandler = ^(GCController *controller){

        [weakSelf displayMessage:@"Pause Button"];

    };

Thanks to Tim on StackOverflow. Read his full answer and in-depth discussion here:

稿源:iOS Dev Diary (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 移动互联 » How to avoid “Capturing ‘self’ strongly in this block is likely to lead to a retain cycle”

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录