69

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

4

3 回答 3

82
@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的文档。

于 2009-05-09T05:25:07.307 回答
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 ];
于 2010-06-22T13:26:41.050 回答
6

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

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

[[NSNotificationCenter defaultCenter] removeObserver:self];

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

[[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
于 2012-12-10T16:18:22.997 回答