cocoa自定义通知示例

有人可以给我看一个Cocoa Obj-C对象的例子,有一个自定义通知,如何触发它,订阅它,并处理它?

@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]; 

有关更多信息,请参阅NSNotificationCenter的文档。

步骤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"); } 

第2步:

 //trigger event [[NSNotificationCenter defaultCenter] postNotificationName:@"eventType" object:nil ]; 

确保在取消分配对象时取消注册通知(观察者)。 苹果文档指出:“在观察通知的对象被释放之前,它必须告诉通知中心停止发送通知”。

对于本地通知,下一个代码是可用的:

 [[NSNotificationCenter defaultCenter] removeObserver:self]; 

对于分布式通知的观察者:

 [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];