views:

218

answers:

3

I've only recently noticed a crash in one of my apps when an object tried to message its delegate and the delegate had already been released.

At the moment, just before calling any delegate methods, I run this check:

if (delegate && [delegate respondsToSelector:...]){
   [delegate ...];
}

But obviously this doesn't account for if the delegate isn't nil, but has been deallocated.

Besides setting the object's delegate to nil in the delegate's dealloc method, is there a way to check if the delegate has already been released just incase I no longer have a reference to the object.

A: 

how about using a counter that you increment everytime you alloc and decrement everytime you dealloc. That way you could detect double allocs and could decide not to use a delegate if the counter isnt nil but the address isnt nil also

yan bellavance
This isn't a good idea, sadly. Objects track their own retain count, which is how they are "automatically" deallocated after the last release. Since he doesn't retain the delegate, this really wouldn't help much anyway.
Quinn Taylor
yeah that was a long shot but I wanted to describe how referencing and dereferencing is managed in the background on some frameworks
yan bellavance
+11  A: 

No. There is no way to tell whether a variable points to a valid object. You need to structure your program so that this object's delegate isn't going away without letting it know first.

Chuck
Thanks. Since the crash it was a simple matter of setting the object's delegate to nil in the delegate's dealloc, but it got me thinking in general :)
Tom Irving
+6  A: 

I assume you're not using GC. In that case, standard convention is that the code that sets the delegate is responsible for setting the delegate-user's reference to nil before allowing the delegate to be deallocated. If you're using GC, you can use a __weak reference for the delegate, allowing the garbage collector to set the reference to nil when the instance is garbage collected.

Barry Wark
+1 for bringing up `__weak` references, and recommending them in the context of GC. In fact, one can argue that using `__weak` in this case is the right thing to do, if (when?) the code is eventually switched to GC in the future.
Quinn Taylor