NSNotificationCenter: addObserver:selector:name:object: - Specifying a single event
NSNotificationCenter: addObserver:selector:name:object: - Specifying a single event
- Subject: NSNotificationCenter: addObserver:selector:name:object: - Specifying a single event
- From: Ari Black <email@hidden>
- Date: Tue, 27 May 2008 15:06:49 -0400
Hello,
Originally I was going to post this as a question, but since I found
the solution while composing the email, I thought I'd simply send it
along for the edification of anyone who might be in a similar situation.
I'm trying to make sure that my application catches all possible
routes for quitting. Quitting from the application menu and a button
can be easily controlled by outlets and IB but I haven't been able to
locate information on how to catch the Quit from the application's
Dock menu.
I thought that NSNotificationCenter's addObserver would be able to
cover this for me, but my searching could not find much on how it
works, specifically what to pass to the name: argument to have it only
notify on application exit.
After rereading the documentation for terminate: on NSApplication, I
found the following:
Then, this method posts an NSApplicationWillTerminateNotification to
the default notification center.
If you pass NSApplicationWillTerminateNotification as the name:
argument, then your notification code will be called by any of the
quit systems. One caveat to this is to make sure that terminate is
called by any buttons or menu items that should close the application.
The easiest way I've found to do this is to make sure that the item is
connected to the terminate: outlet on the File's Owner object in IB.
I believe that you can also accomplish this by assigning a delegate
for your application.
Below is the code that I have implemented to accomplish this. If I
have missed anything, I would be grateful for a correction.
Thank you.
I have these two lines in the awakeFromNib of my main application
object:
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(Quit:)
name:NSApplicationWillTerminateNotification object:NSApp];
I have defined Quit: on my main object, so I pass self as the first
argument. The second is the selector for the Quit: function. Next
NSApplicationWillTerminateNotification, to specify only quitting
events. And last, NSApp, the global application variable that
specifies the current application.
Here is the definition of Quit: stripped of any code specific to my
application:
- (void)Quit:(NSNotification *)note {
}
-------------------------------------
Clockwise turn, heart open.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden