ARC circular reference in objective-c uses delegate

拈花ヽ惹草 提交于 2020-01-13 10:16:12

问题


Hello!

I tried to use a delegate in my app. My project uses ARC

For example, I have protocol X and two object which uses it. In object B I created an instance for object A and set delegate self (A.delegate = self) In runtime I invoke a method callBack (in this point my delegate object is B). After that they all execute the -showResult method.

At what point is a circular reference formed? I understand that this is a problem with the specifier strong, but I don't understand what time it happened, and how to track it.

Thanks!


回答1:


If two objects both maintain strong references to each other (that is, they retain each other), you may have what's known as a 'retain cycle' on your hands. Neither object will ever be deallocated because the other has a strong reference to it (retains it), and so it will never give up its reference (release) the other object.

This situation is common with delegates, where one object (call it A) creates another (B) and sets itself as B's delegate. If A has a strong reference to B so that B won't get deallocated, and B also has a strong reference to A, you have a reference cycle. In order to avoid that, it's common for objects not to retain or keep strong references to their delegates. Make B's reference to A weak instead of strong and the problem goes away.




回答2:


It looks like you keep a strong reference to A in B. Either make it a weak reference or - which is the common practice - make the delegate a weak reference. In the latter case you should make sure to set A's delegate to nil before B is deallocated.



来源:https://stackoverflow.com/questions/9313967/arc-circular-reference-in-objective-c-uses-delegate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!