Short answerInstead of accessing
The If you are using ARC, the semantics of Long answerLet's say you had code like this:
The problem here is that self is retaining a reference to the block; meanwhile the block must retain a reference to self in order to fetch its delegate property and send the delegate a method. If everything else in your app releases its reference to this object, its retain count won't be zero (because the block is pointing to it) and the block isn't doing anything wrong (because the object is pointing to it) and so the pair of objects will leak into the heap, occupying memory but forever unreachable without a debugger. Tragic, really. That case could be easily fixed by doing this instead:
In this code, self is retaining the block, the block is retaining the delegate, and there are no cycles (visible from here; the delegate may retain our object but that's out of our hands right now). This code won't risk a leak in the same way, because the value of the delegate property is captured when the block is created, instead of looked up when it executes. A side effect is that, if you change the delegate after this block is created, the block will still send update messages to the old delegate. Whether that is likely to happen or not depends on your application. Even if you were cool with that behavior, you still can't use that trick in your case:
Here you are passing
This solution avoids the retain cycle and always calls the current delegate. If you can't change the block, you could deal with it. The reason a retain cycle is a warning, not an error, is that they don't necessarily spell doom for your application. If You could also look into using a similar trick above, declaring a reference weak or unretained and using that in the block. For example:
All three of the above will give you a reference without retaining the result, though they all behave a little bit differently: What's best will depend on what code you are able to change and what you cannot. But hopefully this has given you some ideas on how to proceed.
|
|||||||||||||||||||||||||||||||||
|
up vote17down vote |
There’s also the option to suppress the warning when you are positive that the cycle will get broken in the future:
That way you don’t have to monkey around with
|
||||||||||||||
|
up vote7down vote |
I believe the solution without ARC also works with ARC, using the EDIT: Per the Transitioning to ARC Release Notes, an object declared with
|
||||||||||||||||||||
|
up vote6down vote |
For a common solution, I have these define in the precompile header. Avoids capturing and still enables compiler help by avoiding to use
Then in code you can do:
|
欢迎加群互相学习,共同进步。QQ群:iOS: 58099570 | Android: 330987132 | Go:217696290 | Python:336880185 | 做人要厚道,转载请注明出处!