Re: "Capturing 'self' strongly in this block is likely to lead to a retain cycle"
Re: "Capturing 'self' strongly in this block is likely to lead to a retain cycle"
- Subject: Re: "Capturing 'self' strongly in this block is likely to lead to a retain cycle"
- From: Fritz Anderson <email@hidden>
- Date: Mon, 09 Jul 2012 11:03:50 -0500
On 9 Jul 2012, at 10:40 AM, Andreas Grosam wrote:
> The warning "Capturing 'self' strongly in this block is likely to lead to a retain cycle" is issued in this method:
>
> - (void) foo
> {
> [self.operationQueue addOperationWithBlock:^{
> [self bar];
> }];
> }
>
> property operationQueue is declared 'strong'.
>
> I understand the message, that is:
>
> 'self' is strongly retaining _operationQueue which itself strongly retains a block which itself strongly retains 'self'.
No. _operationQueue has nothing to do with it. The capture referred to has only to do with the block. As the warning says, it's a capture of self.
> However, is this a problem in this case? I expect message bar to be queued in the operation queue. Meanwhile all references to 'self' diminish, except the one in the block. The block executes and eventually finishes and releases 'self' - possibly the last reference.
You correctly describe the cycle. In practice, NSOperationQueue probably releases the block when it's done with it, and breaks the cycle, but clang can't know that, so it has to warn of the "likely" cycle.
You can break this by having a strong reference to self that the block can manage independently.
__block MyClass * blockSelf = self;
[self.operationQueue addOperationWithBlock:^{
[blockSelf bar];
blockSelf = nil;
}];
— F
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden