调用调用另一个引用self的方法的块内的方法会导致保留周期吗? [英] Does calling a method inside a block that calls another method referring to self cause a retain cycle?

查看:117
本文介绍了调用调用另一个引用self的方法的块内的方法会导致保留周期吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以 doFirst 在这里导致保留周期吗?

Can doFirst cause a retain cycle here?

@interface Example : NSObject
@property (nonatomic, strong) void (^block)();
@end

@implementation Example

- (void)doFirst
{
    __weak id weakSelf = self;
    self.block = ^ {            
        [weakSelf doSecond];
    };

    self.block();
}

- (void)doSecond
{
    self.value = //...
    // do other stuff involving self
}
@end


推荐答案

与块不同,方法不是对象;他们无法持有对象的永久引用。

Unlike blocks, methods are not objects; they cannot hold a permanent reference to objects.

您的代码不会导致保留周期。 doSecond 中的代码明确引用 self 这一事实并不意味着 self 会保留额外的时间。当您的块调用 doSecond 时,其 self 来自 weakSelf doFirst 内的参考。

Your code would not cause a retain cycle. The fact that the code inside doSecond references self explicitly does not mean that self would get retained an extra time. When your block calls doSecond, its self comes from the weakSelf reference inside doFirst.

注意:当您将块存储为属性时,使用(非原子,复制) 而不是(非原子,强)

Note: When you store blocks as properties, use (nonatomic, copy) instead of (nonatomic, strong).

这篇关于调用调用另一个引用self的方法的块内的方法会导致保留周期吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆