zoukankan      html  css  js  c++  java
  • IOS学习之NSNotificationCenter消息机制

    NSNotificationCenter是 Cococa消息中心,统一管理单进程内不同线程的消息通迅。

     添加观察者接收通知:

    //添加通知中心观察者
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(testMethod:) name:key object:self.person];
    

    参数说明:

              addObserver: 观察者,谁来接收通知;

            selector: 收到通知后调用的方法;

            name: 注册所观察通知的名字

             object: 订阅该通知的对象,如果设置为nil 则接收所有通知

    移除注册观察者:

         //移除某个指定的观察者
        [[NSNotificationCenter defaultCenter] removeObserver:self name:key object:self.person];
        
         //移除所有观察者
        [[NSNotificationCenter defaultCenter] removeObserver:self];

    发送通知:

        //发送带参数的通知
         NSDictionary *dic =@{@"1":@1,@"2":@2};
        [[NSNotificationCenter defaultCenter] postNotificationName:key object:self.person userInfo:dic];
        //发送不带参数的通知
        [[NSNotificationCenter defaultCenter] postNotificationName:key object:self.person];
        
        //发送通知对象
        NSNotification *notification =[[NSNotification alloc]initWithName:key object:self.person userInfo:nil];
        [[NSNotificationCenter defaultCenter]postNotification:notification];

    参数说明:

    postNotificationName:通知名字 ,和注册通知观察者名字一致

    object:通知的发送者

    userInfo:通知传递的参数

    接收通知:

    //收到通知后调用方法
    -(void)testMethod:(NSNotification*)notification
    {
        NSLog(@"notification----->%@",notification);//接收到的通知对象
        id sender =[notification object];//获取发送者对象
        NSLog(@"sender----->%@",sender );
        NSDictionary *userInfo=[notification userInfo];//获取传递参数
        NSLog(@"userInfo----->%@",userInfo );
        
    }

    使用场景:

      1.不同页面之间的通知传值

              

  • 相关阅读:
    The first appliaction for "Hello World!"
    zone
    learn to study
    深入理解 Angular 2 变化监测和 ngZone
    看看吧
    生命周期钩子
    一个简单的todo
    依赖注入
    @Output()
    @Input
  • 原文地址:https://www.cnblogs.com/whoislcj/p/5499064.html
Copyright © 2011-2022 走看看