您的位置:首页 > 移动开发 > IOS开发

IOS学习之NSNotificationCenter消息机制

2016-05-16 18:23 417 查看
NSNotificationCenter是 Cococa消息中心,统一管理单进程内不同线程的消息通迅。

添加观察者接收通知:

//添加通知中心观察者
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(testMethod:) name:key object:self.person];


参数说明:

addObserver: 观察者,谁来接收通知;

  selector: 收到通知后调用的方法;

  name: 注册所观察通知的名字

object: 订阅该通知的对象,如果设置为nil 则接收所有通知

移除注册观察者:

//移除某个指定的观察者
[[NSNotificationCenter defaultCenter] removeObserver:self name:key object:self.person];

//移除所有观察者
[[NSNotificationCenter defaultCenter] removeObserver:self];


发送通知:

//发送带参数的通知
NSDictionary *dic =@{@"1":@1,@"2":@2};
[[NSNotificationCenter defaultCenter] postNotificationName:key object:self.person userInfo:dic];
//发送不带参数的通知
[[NSNotificationCenter defaultCenter] postNotificationName:key object:self.person];

//发送通知对象
NSNotification *notification =[[NSNotification alloc]initWithName:key object:self.person userInfo:nil];
[[NSNotificationCenter defaultCenter]postNotification:notification];


参数说明:

postNotificationName:通知名字 ,和注册通知观察者名字一致

object:通知的发送者

userInfo:通知传递的参数

接收通知:

//收到通知后调用方法
-(void)testMethod:(NSNotification*)notification
{
NSLog(@"notification----->%@",notification);//接收到的通知对象
id sender =[notification object];//获取发送者对象
NSLog(@"sender----->%@",sender );
NSDictionary *userInfo=[notification userInfo];//获取传递参数
NSLog(@"userInfo----->%@",userInfo );

}


使用场景:

1.不同页面之间的通知传值
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: