美文网首页
NSNotificationCenter-----useage

NSNotificationCenter-----useage

作者: AntKing | 来源:发表于2017-03-31 21:56 被阅读0次

注册: [[NSNotificationCenter defaultCenter] addObserver:注册对象 selector:@selector(方法名) name:信息名称 object:nil]
注销: [[NSNotificationCenter defaultCenter] removeObserver:注销对象 name:信息名称 object:nil];
发送信息:[[NSNotificationCenter defaultCenter] postNotificationName:信息名称 object:发信息对象 userInfo:发送消息时 传递的信息(是个字典)];
代码示例:

  • 某个类Class2在适当的时候发送通知
// 发送通知  
//postNotificationName:@"NOTIFICATIONONE" 通知的名字 必须和注册时一样 否则接收不到  
//userInfo:(NSDictionary *)携带的参数 是个字典  
//object:@"888"必须和注册通知时一致 或者注册时填nil,那添加通知的类Class1的添加和移除都要谈nil  
[[NSNotificationCenter defaultCenter] postNotificationName:@"NOTIFICATIONONE" object:@"888"   
Info:@{@"UI":@"Over"}];  

  • 某个类Class1监听通知,delloc方法中对应要有移除通知

// 注册一条通知 就是接收方接受参数的  
    // [NSNotificationCenter defaultCenter] 通知中心 是个单例类  
    // name:@"NOTIFICATIONONE"通知的名字 最好是全大写 做到见名知意  
    //selector:收到通知后触发的方法  
    //object:发送方对象, 可以写nil,如果写的话发送信息和注册时要一致  
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationInfo:)   
name:@"NOTIFICATIONONE" object:@"888"];  

  • 某个类Class1必须移除通知
-(void)dealloc  
{  
    // 销毁通知  
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NOTIFICATIONONE" object:@"888"];  

}  
  

相关文章

网友评论

      本文标题:NSNotificationCenter-----useage

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