代碼塊block :capturing self strongly in this block is


在代碼塊中使用對象的成員時(成員變量是屬性strong,MRC估計是retain時效果同樣,使用方法時也同樣):ui

警告:this

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

意思應該是block會retain一次,因此使用前最好 __block MyClass* bObject = self;spa


from:code

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


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

Andreasget

相關文章
相關標籤/搜索