Cocoa自定义通知示例

时间:2009-05-09 05:10:25

标签: objective-c cocoa notifications

有人可以向我展示一个Cocoa Obj-C对象的示例,带有自定义通知,如何触发它,订阅它并处理它?<​​/ p>

3 个答案:

答案 0 :(得分:81)

@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 :(得分:45)

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

答案 2 :(得分:5)

确保在取消分配对象时取消注册通知(观察者)。 Apple文档声明:“在观察通知的对象被解除分配之前,它必须告知通知中心停止向其发送通知”。

对于本地通知,下一个代码适用:

[[NSNotificationCenter defaultCenter] removeObserver:self];

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

[[NSDistributedNotificationCenter defaultCenter] removeObserver:self];