IOS|IOS NSNotification 5分钟学会通知中心

名称 通知中心
解释 【IOS|IOS NSNotification 5分钟学会通知中心】广播机制,将接收到的消息根据内部消息转发标,将消息转发给对应的对象。常用在不通控制器之间的通信。
重点记住

  • 可以实现跨层传值,比如A页面push到B页面,B页面push到C页面,如果让A页面知道C页面修改什么使用通知模式很方便
  • 一对多模式,可以注册多个相同的name通知,一个地方发出通知,多个监听者响应通知。
  • add和remove要成对出现,否则会出现隐藏的异常
  • NSNotificationCenter处理单个进程之间的通信,NSDistributedNotificationCenter 处理多个进程之间的通信
  • NSNotificationCenter是同步处理方式,NSNotificationQueue是异步处理方式
关键步骤
  1. 注册通知:在需要接收通知的地方注册观察者
  2. 发送通知:在需要的时候发出通知
  3. 接收通知:处理接收到的通知
  4. 移出通知:不使用的时候要移出通知
核心代码
@property (nonatomic,retain) NSNotification * hs_notice; /** 注册一个通知消息到通知中心 */ -(void)func_regist { //获取通知中心单例对象 NSNotificationCenter * center = [NSNotificationCenter defaultCenter]; //添加当前类对象为一个观察者,name和object设置为nil,表示接收一切通知 [center addObserver:self selector:@selector(notification_notice:) name:@"123" object:nil]; }/** 接收到通知 @param sender <#sender description#> */ -(void)notification_notice:(NSNotification *)sender { NSLog(@"收到消息"); }/** 发送一个通知 ps:在另外的控制器里发送通知 */ -(void)func_post { //创建一个消息对象 self.hs_notice = [NSNotification notificationWithName:@"123" object:nil userInfo:@{@"1":@"123"}]; //发送消息 [[NSNotificationCenter defaultCenter] postNotification:self.hs_notice]; }/** 移出通知 */ -(void)func_remove { [[NSNotificationCenter defaultCenter] removeObserver:self]; }

QQ :384302147

    推荐阅读