iOS通知中心 NSNotificationCenter详解

NSNotificationCenter的适用场景,原理机制,使用步骤等。

通知中心的使用顺序:先确保注册了观察者,因为发送通知是一瞬间的事,如果没有注册观察者,发送通知后再注册是不会收到的。

总结:通知只会发送给当前监听着的对象。

代码

//注册通知  在关心该通知的页面注册监听

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

 

//发送通知  一定要确保有注册了监听该通知才行

NSDictionary *dict =@{@"key":@"Value"};

    //创建通知

    NSNotification *notification =[NSNotification notificationWithName:@"tongzhi" object:nil userInfo:dict];

    //通过通知中心发送通知

    [[NSNotificationCenter defaultCenter] postNotification:notification];

//收到通知后回调的方法

- (void)tongzhi:(NSNotification *)text{

    NSLog(@"%@",text.userInfo[@"key"]);

    NSLog(@"-----接收到通知------");  

}

//在不需要接收通知的时候一定要移除监听

  [[NSNotificationCenter defaultCenter] removeObserver:self];

http://www.wtoutiao.com/a/1385824.html  这一篇总结得很不错

待总结...

原文地址:https://www.cnblogs.com/GetLastError/p/4810990.html