How do I check if a delegate is valid?

I am doing something like this:

@protocol CallbackDelegate
-(void) performCallback;
@end

@interface MyObject : NSObject {
   id<CallbackDelegate> delegate;
}

-(void)AsyncFuncCall;

@end

@property (nonatomic, assign) id<CallbackDelegate> *delegate;

      

The code that owns MyObject

sets the delegate to receive the callback function:

MyObject *myobject = [[MyOject alloc] init];
myobject.delegate = x;

      

Then in MyObject

, as a result of the call to the async function, I return to the delegate:

-(void)AsyncFuncCall {
   [delegate performCallback];
}

      

Most of them generally work well, except when my delegate was freed as a result of an actual memory cleanup. In this case, I just don't want to do the callback

Does anyone know the best way to check if a delegate is actually delegated?

I've tried all sorts of things like:

if (delegate != nil) {
   ...
}

      

no luck.

+1


source to share


1 answer


Your delegate should disable the delegate's myObject property in their dealloc to avoid this:

- (void) dealloc {
  if (myObject.delegate == self) myObject.delegate = nil;
  [super dealloc];
}

      



Alternatively, but not recommended, you can keep the delegate. However, this may result in the cycle being saved .

+4


source







All Articles