美文网首页
NSNotificationCenter通知中心的使用

NSNotificationCenter通知中心的使用

作者: 雷霸龙 | 来源:发表于2017-05-05 18:53 被阅读10次

在你要发送的消息的地方发送消息,这里主要有三种:
第一种:只是发送消息,没有需要传递的参数

[[NSNotificationCenter defaultCenter] postNotificationName:@"postTest" object:nil userInfo:nil];

第二种:传递一个参数

[[NSNotificationCenter defaultCenter] postNotificationName:@"postTest" object:@"詹姆斯" userInfo:nil];

第三种:传递多个参数(可以用字典就行传递)

NSDictionary * dict = @{@"name":@"詹姆斯", @"team":@"Cleveland"};
[[NSNotificationCenter defaultCenter] postNotificationName:@"postTest" object:nil userInfo:dict];

接收消息要在需要接收的地方注册观察者,方法可以通用,这里的object选择nil就是接收所有消息,当然你可以选择只接收指定消息

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealWithMessage:) name:@"postTest" object:nil];

然后可以处理接收的消息

- (void)dealWithMessage:(NSNotification *)notification
{
    NSLog(@"%@", notification.object);
    NSLog(@"%@", notification.userInfo);
}

相关文章

网友评论

      本文标题:NSNotificationCenter通知中心的使用

      本文链接:https://www.haomeiwen.com/subject/asystxtx.html