Tom W
Tom W

Reputation: 578

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.

Upvotes: 12

Views: 6688

Answers (2)

Jim
Jim

Reputation: 73966

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.

Upvotes: 8

Yannick Reifschneider
Yannick Reifschneider

Reputation: 454

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;

Upvotes: 22

Related Questions