سؤال

Hello!

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

enter image description here

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!

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top