objective-c Cocoa 自定义通知示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/842737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:31:09  来源:igfitidea点击:

Cocoa Custom Notification Example

objective-ccocoanotifications

提问by mattdwen

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?

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

回答by Jason Coco

@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.

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

回答by mracoker

Step 1:

第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:

第2步:

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

回答by Grigori A.

Make sure to unregister notification (observer) when your object is deallocated. Apple documentation states: "Before an object that is observing notifications is deallocated, it must tell the notification center to stop sending it notifications".

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

For Local Notifications the next code is applicable:

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

[[NSNotificationCenter defaultCenter] removeObserver:self];

And for observers of distributed notifications:

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

[[NSDistributedNotificationCenter defaultCenter] removeObserver:self];