有人可以给我展示一个带有自定义通知的 cocoa Obj-C对象示例,如何触发,订阅和处理它?
最佳答案
@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的文档。
关于objective-c - cocoa 定制通知示例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/842737/