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的文档.
小智 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)
取消分配对象时,请务必取消注册通知(观察者).Apple文档声明:"在观察通知的对象被解除分配之前,它必须告知通知中心停止向其发送通知".
对于本地通知,下一个代码适用:
[[NSNotificationCenter defaultCenter] removeObserver:self];
Run Code Online (Sandbox Code Playgroud)
对于分布式通知的观察者:
[[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
48899 次 |
| 最近记录: |