通知中心

来源:互联网 发布:阅微草堂笔记 知乎 编辑:程序博客网 时间:2024/04/27 20:20
  1. 获取通知中心,注册一个观察者和事件
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    1. 在通知中心中, 添加一个观察者和观察者事件
      [center addObserver:self selector:@selector(receiveNotification:) name:@”放学” object:nil];
      // 参数1:负责响应事件的观察对象
      // 参数2:一旦收到消息,观察者要执行的方法
      // 参数3:观察者要监听的事件
      // 参数4:可以限定消息发出者
  2. 收到通知中心的消息时 观察者(self)要调用的方法
    • (void)receiveNotification:(NSNotification *)noti
      {
      // 4,
      NSLog(@”%@”, noti.object);
      self.view.backgroundColor = [UIColor orangeColor];
      }
    • (void)ClichButton:(UIButton *)button
      {
      // 3, 通知中心的使用
      // 发送一个消息
      NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
      // 参数1:发送消息的事件名(必须一致)
      // 参数2:可以使用这个参数,传递一个对象给观察者
      // 参数3:一些消息的参数信息(系统用得较多)
      [center postNotificationName:@”放学” object:@”钥匙” userInfo:nil];
      [self.navigationController popToRootViewControllerAnimated:YES];
      }
  3. 只要注册一个观察者 一定要在类的dealloc方法中 移除掉自己的观察者身份
    在ARC下一样
    • (void)dealloc
      {
      NSNotificationCenter *center = [NSNotificationCenter defautCenter];
      [Center removeObject:self];
      [super dealloc];
      }
0 0