【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
类TestClass的实现:
@implementation TestClass
- (void) dealloc
{
// If you don't remove yourself as an observer, the Notification Center
// will continue to try and send notification objects to the deallocated
// object.
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
- (id) init
{
self = [super init];
if (!self) return nil;
// Add this instance of TestClass as an observer of the TestNotification.
// We tell the notification center to inform us of "TestNotification"
// notifications using the receiveTestNotification: selector. By
// specifying object:nil, we tell the notification center that we are not
// interested in who posted the notification. If you provided an actual
// object rather than nil, the notification center will only notify you
// when the notification was posted by that particular object.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(receiveTestNotification:) // 响应时调用的函数,因为函数有参数,所有后带冒号
name:@"TestNotification" // 必须是字符串
object:nil];
return self;
}
- (void) receiveTestNotification:(NSNotification *) notification
{
// [notification name] should always be @"TestNotification"
// unless you use this method for observation of other notifications
// as well.
if ([[notification name] isEqualToString:@"TestNotification"]) // 这个判断很有必要,其他notification name也可能执行该函数
NSLog (@"Successfully received the test notification!");
}
@end
在另外一个类中:
- (void) someMethod
{
// All instances of TestClass will be notified
[[NSNotificationCenter defaultCenter]
postNotificationName:@"TestNotification"
object:self];
}
当调用someMethod方法时,会触发TestClass中的receiveTestNotification方法。
传递数据
如果需要传递数据,需要把receiveTestNotification
修改成:
- (void) receiveTestNotification:(NSNotification *) notification
NSDictionary *userInfo = [notification object];
}
如此触发:
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:myObject forKey:@"someKey"];
[[NSNotificationCenter defaultCenter] postNotificationName: @"TestNotification" object:userInfo];
来源:oschina
链接:https://my.oschina.net/u/940565/blog/804803