Note that there are some explanatory texts on larger screens.

plurals
  1. POReference counting when implementing a delegate for custom class in ObjectiveC
    text
    copied!<p>I have two classes, ClassA that will instantiate ClassB and pass off a method as a delegate. ClassB will eventually invoke ClassA's delegate. Do I need to add a retain on ClassA when ClassB stores it?</p> <p>I'm following the "Implementing a Delegate for a Custom Class" from the "Cocoa Fundamentals Guide: Communicating with Objects" but the sample code demonstrated doesn't seem to take memory management into account.</p> <p>ClassA will set the delegate and expect to be called back later when ClassB is done with it's work.</p> <pre><code>@implementation ClassA -(void)launchSomething { ClassB *classB = [[ClassB alloc] init]; [classB setCallback:self withSelector:@selector(deferredWork)]; // do some other stuff, assign class B to some View and eventually release class B } -(void)deferredWork { NSLog(@"this is the method that will be deferred till some point in time"); } </code></pre> <p>Header file for the ClassB that'll store and then later invoke the delegate:</p> <pre><code>@interface ClassB id targetObject; SEL targetMethod; -(void) setCallback:(id)anObject withSelector:(SEL)aMethod </code></pre> <p>ClassB's implementation:</p> <pre><code>@implementation ClassB -(void) setCallback:(id)anObject withSelector:(SEL)aMethod { // QUESTION: Do I need to add a 'retain' here on the targetObject? targetObject = anObject; targetMethod = aMethod; } -(void) someWorkLater { if ( [targetObject respondsToSelector:@selector(targetMethod)] ) { // invoke the target object with the specific method [targetObject targetMethod]; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload