简体   繁体   中英

Accessing self in NSBlockOperation – retain cycle?

self.operationQueue = [[NSOperationQueue alloc] init];
[self.operationQueue addOperationWithBlock:^{
    [self doSomethingElse];        
}];

- (void)doSomethingElse {
    [self doAnother];
}

Does this create a retain cycle? I keep a reference to the operation queue but not the operation. Thoughts?

This could create a retain cycle. Create a weak pointer to self and use that:

_weak MyObject *weakSelf = self;

EDIT:

In your block, create a strong reference back to self. Evaluate your pointer to make sure it's valid, and you're safe. Your snippet (based on what you've described, then), should read:

self.opeartionQueue = [[NSOperationQueue alloc] init];
_weak MyObject *weakSelf = self;
[[self operationQueue] addOperationBlock:^{

    _strong MyObject *strongSelf = weakSelf; // Obtain a strong reference so our pointer won't dangle out from under us...

    if(strongSelf) // Make sure it's valid
    {
        [strongSelf doSomethingElse]; // Do your work
    }
}

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