This post continues the common error of block-the circular reference.
Circular references are not detectable by many beginners, and the reason for this is that the code in the block will strongly refer to the object .
Reader read example code 1 and consider if the object created by example code 1 can be destroyed normally?
Example code 1:
* Mark changes the code to a method called self-(Nsmutablearray * (_myblocks ===-= (^sum) (,) = ^ (x, automatically called when the Mark object is freed-(
The result is not normally released. Readers may wish to try out in Xcode.
The reason for this is that self is present in the block code:
Int (^sum) (int, int) = ^ (int x, int y) {return [self sum:x y:y];};
At this point the block of sum has a strong reference to self, plus self to myblocks strong references:
@property (nonatomic, strong) Nsmutablearray *myblocks;
And when the sum block is added to the array, it is strongly referenced by the array:
[Self.myblocks Addobject:sum];
A circular reference is formed between these three references, such as:
The result of a circular reference is that the object cannot be released!
How can a programmer dismiss a circular reference when confronted with such a problem?
The following solutions are available:
1. Do not refer to self and other local variables in the block code;
Int (^sum) (int, int) = ^ (int x, int y) {return [self sum:x y:y];};
Modified into
Int (^sum) (int, int) = ^ (int x, int y) {return x + y;};
2. Using the __weak keyword, you can declare a local variable as a weak reference
Such as:
-(instancetype) init{self = [super init]; if (self) {int (^sum) (int, int.) = ^ (int x, int y) {return [self sum:x y:y]; }; [Self.myblocks Addobject:sum]; } return self;}
Modified to:
-(instancetype) init{self = [super init]; if (self) {__weak demoobj *weakself = self; Int (^sum) (int, int) = ^ (int x, int y) {return [weakself sum:x y:y]; }; [Self.myblocks Addobject:sum]; } return self;}
The block's circular reference says this, the next article continues to explain the block's common mistakes
Common errors in iOS block (ii)--circular references