简体   繁体   中英

Does block object cause retain cycle?

I have this code:

@implementation example
{
    NSString *myObject;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    __block NSString* blockObject = myObject;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0),^(void){
        blockObject = @"Hello world";    
    });
}

Now because I am using __block, a strong reference is made to self, because I am accessing an instance variable by reference and not by value.

So the above code is the same as:

@implementation example
{
    NSString *myObject;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0),^(void)  {
        myObject = @"Hello world";    
    });
}

So dealloc method will not called until the block exit. My compiler use arc!

__block NSString* blockObject = myObject;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0),^(void){
        blockObject = @"Hello world";    
    });

The above code will not strongly hold the self and thus your dealloc will be called before the block exits. Why it will not strongly hold the self is because you are creating a new variable blockObject and block will strongly hold this variable not the ivar thus not retaining the self


dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0),^(void)  {
        myObject = @"Hello world";    
    });

The above code will strongly hold the self and dealloc will not be called until block exits.

The two example in your question are in fact very different.

The first results in NO CHANGE to your instance variable myObject whereas the second changes it to "Hello world".

Usually if I have to access instance variables, I write something like this... fyi. pseudocode

__weak typeof(self)weakSelf = self;

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0),^(void)  {
    __strong typeof(weakSelf)strongSelf = weakSelf;
    strongSelf->myObject = @"Hello world";    
});

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