Cocoa自定义通知示例

mat*_*wen 67 cocoa notifications objective-c

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

Jas*_*oco 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];
Run Code Online (Sandbox Code Playgroud)

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

  • 松耦合.请注意"//其他地方"注释...通知是一种广播消息.任何对象实例都可以侦听通知,并且不需要符合任何特定的委托协议或类似协议.可能有许多实例正在侦听单个消息.发送者不需要指向它希望通知的对象实例. (3认同)

小智 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");
}
Run Code Online (Sandbox Code Playgroud)

第2步:

//trigger event
[[NSNotificationCenter defaultCenter]
    postNotificationName:@"eventType"
    object:nil ];
Run Code Online (Sandbox Code Playgroud)


Gri*_* A. 5

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

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

[[NSNotificationCenter defaultCenter] removeObserver:self];
Run Code Online (Sandbox Code Playgroud)

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

[[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
Run Code Online (Sandbox Code Playgroud)