ARC circular reference in objective-c uses delegate

Hello!

I tried using a delegate in my application. My project uses ARC

enter image description here

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

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

Thanks!

+4
source share
2 answers

If two objects support strong links to each other (that is, save each other), you may have what is called a โ€œsave cycleโ€ on your hands. No object will ever be released, because the other has a strong reference to it (saves it), and therefore it will never give up its link (release) of another object.

This situation is typical for delegates, where one object (calls it A) creates another (B) and sets itself up as delegate B. If A has a strong link to B, so B will not be released, and B also has a strong link to A, you have a reference loop. To avoid this, it is not recommended for objects to maintain or maintain strong references to their delegates. Link B to weak, not strong, and the problem goes away.

+13
source

It looks like you are holding a strong link to A in B. Either make it a weak link or - as is common practice - make the delegate a weak link. In the latter case, you must set A delegate to nil before B is released.

+1
source

Source: https://habr.com/ru/post/1396864/


All Articles