Cocoa Custom Notification Example

mattdwen picture mattdwen · May 9, 2009 · Viewed 49.4k times · Source

Can someone please show me an example of a Cocoa Obj-C object, with a custom notification, how to fire it, subscribe to it, and handle it?

Answer

Jason Coco picture Jason Coco · May 9, 2009
@implementation MyObject

// Posts a MyNotification message whenever called
- (void)notify {
  [[NSNotificationCenter defaultCenter] postNotificationName:@"MyNotification" object:self];
}

// Prints a message whenever a MyNotification is received
- (void)handleNotification:(NSNotification*)note {
  NSLog(@"Got notified: %@", note);
}

@end

// somewhere else
MyObject *object = [[MyObject alloc] init];
// receive MyNotification events from any object
[[NSNotificationCenter defaultCenter] addObserver:object selector:@selector(handleNotification:) name:@"MyNotification" object:nil];
// create a notification
[object notify];

For more information, see the documentation for NSNotificationCenter.