Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C Delegates with ARC

I'm writing a class that has callbacks to a delegate object, but am having problems with ARC.

e.g. I have ObjectA (the delegate), which conforms to ProtocolA, and ObjectB which is the object that calls back to the delegate. I'm storing ObjectA as a @property in ObjectB.

In this situation, which variables should be strong, and which should be weak references? I need to avoid the situation where passing 'self' from ObjectA to ObjectB to set the delegate results in a cast from a strong to a weak pointer.

like image 798
Tom W Avatar asked Nov 07 '11 20:11

Tom W


2 Answers

To avoid circular references, save the delegate of ObjectB as a weak reference. Because ObjectA "owns" ObjectB, ObjectA should not be released, while ObjectB has a reference to it. So write:

    @property (weak, nonatomic) id <ObjectBDelegate> delegate;
like image 111
Yannick Reifschneider Avatar answered Nov 02 '22 03:11

Yannick Reifschneider


Delegate properties should usually be weak. An object which passes messages to a delegate doesn't "own" the delegate, in fact it's usually the other way around.

like image 20
Jim Avatar answered Nov 02 '22 03:11

Jim