简体   繁体   中英

Does calling a method inside a block that calls another method referring to self cause a retain cycle?

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.

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) .

No It won't. Because It just point to method which won't hold whatwhere inside methods which just an reference as like object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM