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?
+11
A:
@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.
Jason Coco
2009-05-09 05:25:07
A:
Step 1:
//register to listen for event
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(eventHandler:)
name:@"eventType"
object:nil ];
//event handler when event occurs
-(void)eventHandler: (NSNotification *) notification
{
NSLog(@"event triggered");
}
Step 2:
//trigger event
[[NSNotificationCenter defaultCenter]
postNotificationName:@"eventType"
object:nil ];
mracoker
2010-06-22 13:26:41