简体   繁体   中英

Objective-C Delegates with ARC

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

eg 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.

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM