Re: Notifications from an object's dealloc method?
Re: Notifications from an object's dealloc method?
- Subject: Re: Notifications from an object's dealloc method?
- From: Chris Kane <email@hidden>
- Date: Sat, 7 Jul 2001 06:56:32 -0700
On Friday, July 6, 2001, at 07:31 PM, Jonathan Wight wrote:
I have an object that is trying to send a notification message from it's
dealloc method. Unfortunately the notification handler never receives
the
notification (although it does if I send the message from outside the
dealloc method).
Is it legal to send notifications from the dealloc function? I am
trying to
send the message _before_ I called [super dealloc].
There isn't anything special about being in -dealloc wrt notifications,
except sending a notification from there might be dangerous (a note on
that later).
Could something you're doing be unregistering notification-registrations
for that object? Are you doing the notification first thing in -dealloc?
Obviously if you're doing a "remove" operation on the notification
center earlier in the method, you'd probably notice that. Could some
other method you're calling be doing a generic remove relative to that
object, on the center (for example, one can tell the center to remove
all registrations with such-and-such an object)? Or, more subtly, is
the notification getting to one or more objects that might be doing this
in their notification handler (reasoning might be like "well, this
object is going away so let's get rid of any notification-registrations
about it")?
Now, once in -dealloc, an object is going away. (It's possible, I
suppose, that even if you aren't doing [super dealloc], ie, decide to
"not really deallocate", that the object might still get destroyed in
some cases, though I don't know of any.) But in any case, passing
"self" from this context to any other method (the most straightforward
of the ways to get into trouble) is potentially a problem. What if some
object/"method" decides to hold onto the parameter (self), possibly with
a -retain, possibly not? It's about to be destroyed.
Or worse (and I've had to deal with this in the past several times),
somebody might decide to -retain AND -release (or -autorelease). Well,
the ref count had fallen to none and the thing is being destroyed. The
release may see the ref count again zero (*) and start the destruction
again (trigger a call to -dealloc). Crash on accessing bad data, or
infinite recursion leading to crash, or something more subtle.
(*) This is due to the fact that usually one reference count is implicit
in the existance of the object -- except during the special case of in
the -dealloc method! Depends on if the class is storing the ref count
itself and how it's doing that.
So it's tricky to "give 'self' out" in this context when you don't know
what might be done with parameters. Sending a notification which
references the object "self" being destroyed certainly qualifies.
Chris Kane
Cocoa Frameworks, Apple