在你要发送的消息的地方发送消息,这里主要有三种:
第一种:只是发送消息,没有需要传递的参数
[[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);
}
网友评论