代码块block :capturing self strongly in this block is


在代码块中使用对象的成员时(成员变量是属性strong,MRC估计是retain时效果一样,使用方法时也一样):

警告:

capturing self strongly in this block is likely to lead to a retain cycle

意思应该是block会retain一次,所以使用前最好 __block MyClass* bObject = self;


from:

I get the mentioned warning in my code and I'm wondering if this a possibly issue in my case:

ARC enabled.
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'.

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.

Additionally, in this case, it is required that 'self' must not be destroyed prematurely - that is, before message bar finished.

Doesn't break the cycle automatically - and isn't this warning over-alert?

Thanks for clarification!

> 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;
> }];


Thank you Fritz for your answer.

But if I break the cycle and if I understand it correctly, 'self' won't be retained anymore within the block. If there are no more references to 'self' (except one possibly within the block), I fear 'self' will be destroyed before the block executes. I do require, though, that 'self' will be valid as long as the block is not finished.

Note: I'm using ARC in which case a retainable pointer declared with __block will be retained (as opposed to manual ref counting), so I should use __weak or __unsafe_unretained instead of __block to break the cycle (if that is what I have to do).

Andreas




你可能感兴趣的:(代码块block :capturing self strongly in this block is)