Hiya,
I'm 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 up a delegate to recieve the callback function:
MyObject *myobject = [[MyOject alloc] init];
myobject.delegate = x;
Then in MyObject, as a result of an asynchronous function call I'll signal back to the delegate:
-(void)AsyncFuncCall {
[delegate performCallback];
}
All seems to work well most of the time, except for the occasions where my delegate has been freed up as a result of valid memory cleanup. In this case, I simply want to not perform the callback
Does anyone know the best way to check to see if a delegate is valid?
I've tried all sorts of things such as:
if (delegate != nil) {
...
}
with no luck.
Thanks in advance!
Nick.
From stackoverflow
-
Your delegate should nil out myObject's delegate property in its dealloc to avoid this:
- (void) dealloc { if (myObject.delegate == self) myObject.delegate = nil; [super dealloc]; }Alternatively, but not recommended, you could retain the delegate. However, this can lead to a retain cycle.
Nick Cartwright : Brilliant, this looks like it should work also! I was previously retaining delegates to get around the problems I was having - but my code looked so messy and it didn't quite feel right. Your solution above looks like it solves this. Thanks again, Nick.
0 comments:
Post a Comment