Re: Notification Issue
Re: Notification Issue
- Subject: Re: Notification Issue
- From: Chris Kane <email@hidden>
- Date: Wed, 24 Sep 2003 12:53:57 -0700
On Sep 11, 2003, at 11:23 AM, John Nairn wrote:
My application has two types of documents and one type needs to know if
the other one has just closed. I implemented the process by posting a
notification in the dealloc method of the second document type with
object self.
But then I noticed in Apple documentation on posting notification that:
notificationWithName:object:
+ (id) notificationWithName: (NSString *) aName object: (id) anObject
Returns a notification object that associates the name aName with the
object anObject .aName may not be nil .
This method copies aName and retains anObject .
My concern is that self (passed as anObject) will be retained while
being deallocated. It seems to work fine, but is such a notification
posting in delloc method forbidden?
To provide an authoritative answer on this, sending notifications about
self from a -dealloc method is absolutely a BAD idea. I've seen
examples of projects bitten by this, and they had to remove the
notification, or at least remove it from there or change it around a
bit, to make the code work. If you find it works for you, then you are
getting lucky in the particular execution pattern that happens to
occur, not because it fundamentally should work.
Your object is going away in -dealloc, and no amount of retaining is
going to stop it, and passing self to any method which may retain it
(particularly including ones which you don't know what they might do)
can be tantamount to passing a pointer to a freed object, if anything
tries to keep ahold of the object. In the notification case, all the
notification handlers are going have such an opportunity to get the
object and hold onto it or pass it off to something else in an infinite
variety of ways (including, but not limited to, holding onto the
notification object itself too!).
Moving the notification posting to the -release method is not
necessarily the solution either, except with complicated assist code to
get you over the complicated last retain case. (Basic non-complicated
code will generally quickly crash due to infinite recursion, for
example. Why is left as a thought experiment to the reader.)
Chris Kane
Cocoa Frameworks, Apple
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.