Problem
We know that in order to avoid circular references when using block, it is often necessary to use weakself and strongself to write the following code:
typeof (self) weakself = self;[ Self dosomeblockjob:^{ typeof(weakself) strongself = weakself; if (strongself) { ... }}];
Then ask: when in block with self, do not need to use weak self?
Answer
The weak self is not required when the block itself is not owned by the own, but is held by another object and does not produce a circular reference. The most common code is UIView animation code, and we animateWithDuration:animations do not need to use the weak self when animating with the UIView method, because the reference holding relationship is:
- One of UIView's animated objects holds a block
- Block holds the self
Since self does not hold a block, there is no circular reference because there is no need to use weak self.
[UIView animatewithduration:0.2 animations:^{ 1;}];
When the animation is finished, the UIView will end up holding the block, and if no other object holds the block, the Block object will be released and the block will release the hold for self. The entire memory reference relationship is lifted.
Study Questions
If you think the above problem is too simple, consider the following two topics:
- Why do I have to write a strong self in block, what if I don't write it?
- There is no such a demand scenario, block will produce circular references, but the business needs you can not use weak self? If so, give an example and explain how to solve the circular reference problem in this case.
IOS face Question (ii): When to use weakself in block--from Tang Qiao