有人可以向我展示一个带有自定义通知的 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];
有关更多信息,请参阅文档NS通知中心 http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html#//apple_ref/doc/uid/20000219-2831.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)