消息中心

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.title = @"第一页";
    self.view.backgroundColor = [UIColor cyanColor];
    [self createBtn];
    
    second = [[SecondViewController alloc]init];

    //添加消息的接收者--- 为消息中心添加观察者
    //消息对整个工程都是可见 在整个工程的任意函数中都能接收消息
    //消息中心只有一个 发送的消息只能通过消息的名字辨别

    //1、添加的是观察者对象指针
    //2、接收到消息以后做出的操作(触发的方法)
    //3、消息的名称
    //4、设置为nil
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeBackGroundColor:) name:@"changeColor" object:nil];
}
//接收到消息触发的方法 必须带有参数 参数的类型是NSNotification 通过这个参数获取消息的内容
-(void)changeBackGroundColor:(NSNotification *)notification
{
    //<1>获取消息的内容  [notification object] 内容是 [UIColor yellowColor]
    UIColor * color = [notification object];
    //object就是发送消息的时候的消息内容(object)
    //<2>
    self.view.backgroundColor =color;

}
-(void)pressBtn:(id)sender
{
    //通知
    //通知又叫做消息中心
    //发送的消息 在整个工程都是可见的
    
    //<1>需要创建消息中心对象[NSNotificationCenter defaultCenter];
    //<2>消息中心是一个单例方法创建 证明整个工程中该消息有且只有一个
    //<3>一个工程中可以发送多个消息 也可以一个消息有多个接收者
    //<4>发送消息的时候 整个工程中的消息的名称一定要唯一
    
    //postNotificationName:   name必须唯一 并且接收者接收消息的名称一定要和发送消息的名称对应 否则找不到
    //object:消息的内容 消息的内容可以是任意类型的对象指针(包括nil)
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeColor" object:[UIColor yellowColor]];
  [self.navigationController popToRootViewControllerAnimated:YES];
}
原文地址:https://www.cnblogs.com/sayimba/p/5672937.html