SoFunction
Updated on 2025-03-10

Detailed explanation of block loop reference problem in Objective-C

Target: Self will not be released during the execution of the block; it can be released after execution.

initial

Using self directly in block will strongly refer to it.

 = ^() {
 [self doSomething];
};

Or the object's properties are used

 = ^() {
 NSString *str = _str;
 NSString *str2 = ;
};

In such a case, self strongly references block, and block also holds the object, resulting in a circular reference.

It should be noted that this problem will only occur when self strongly references blocks. Generally, inline blocks used when using GCD or NSOperation will not have circular references.

Join weak self

__weak __typeof(self) weakSelf = self;
 = ^() {
 [weakSelf doSomething];
};

In this way, self holds block, but block is a weak reference to self, so it will not cause a circular reference.

And in the process of [weakSelf doSomething], self will not be released, perfect.

But what if so?

__weak __typeof(self) weakSelf = self;
 = ^() {
 [weakSelf doSomething];
 [weakSelf doSomething2];
};

Between [weakSelf doSomething] and [weakSelf doSomething2], self may be released. This can lead to strange problems.

Join strong self

__weak __typeof(self) weakSelf = self;
 = ^() {
 __strong __typeof(self) strongSelf = weakSelf;
 [strongSelf doSomething];
 [strongSelf doSomething2];
};

In this way, the block does not hold self, and can ensure that the block is not released during execution, truly achieving the initial goal.

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support.