Problem
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.
Answer
The scenario where you need to not use weak self is that you need to construct a circular reference so that both sides of the reference are present. For example, you have a background task, you want to notify another instance when the task is finished. In our open source Ytknetwork network Library Source code, there is such a scenario.
In the Ytknetwork library, each of our network request APIs will hold the callback block, the callback block will hold self, and if self also holds the network request API, we construct a circular reference. Although we have constructed a circular reference, because at the end of the network request, the network request API will voluntarily release the hold of the block, so the entire loop chain is untied, the circular reference is broken, so there is no memory leak problem. The code is really simple, as follows:
// ytkbaserequest.m-(void) clearcompletionblock { // nil out to break The retain cycle. Self.successcompletionblock = nil; = Nil;}
In summary, there are two main ways to solve circular reference problems:
- The first approach is "avoid beforehand", where we use weak weak references where a circular reference is generated to avoid a circular reference.
- The second approach is to "recover afterwards," and we know for sure that there will be a circular reference, but we are actively disconnecting a reference in the ring at a reasonable position, allowing the object to be recycled.
Study Questions
The problem with the next issue is that the weak variable is automatically set to nil when the reference count is 0 o'clock, how is this feature implemented?
IOS face Question (iv): when the block needs to construct circular references--from Tang Qiao