Weak references in blocks and retain cycles

后端 未结 2 818
野性不改
野性不改 2021-01-13 09:25

In this question, I asked about the following code and retain cycles:

__weak Cell *weakSelf = self;
NSBlockOperation *op = [NSBlockOperation blockOperationWi         


        
2条回答
  •  离开以前
    2021-01-13 10:06

    I can't tell you the reason for the retain-cycle in your second example, because I don't know MBItem, but there are two different usage patterns with blocks.

    If you expect your block to execute in any case, then you can just use self in the block:

    [startSomeOperationWithCompletionBlock:^{
        [self doSomeThing];
    }];
    

    The block retains a reference to self, so that self is not deallocated before the block is executed. But after the block has executed, this reference (and the retain cycle) is gone.

    If you possibly want that self is deallocated before the block has executed, or if it is possible that the block will not be called at all, then you have to use a weak reference and check the value inside the block:

    __weak MyClass *weakSelf = self;
    [startSomeOperationWithCompletionBlock:^{
        MyClass *strongSelf = weakSelf;
        if (strongSelf) {
            [strongSelf doSomeThing];
        }
    }];
    

    The block does not retain self in this case, so that self can be deallocated. In that case, weakSelf is set to nil automatically. Therefore, if the block is executed finally, you have to check first if weakSelf is still valid. (Or you can just use it, because sending messages to nil is a no-op.)

    Assigning a strong reference strongSelf inside the block prevents self from being deallocated while the block is executing.

提交回复
热议问题