zoukankan      html  css  js  c++  java
  • NSNotification监听广播

         在处理监听传值的过程中,有一种广播机制,它通过注册广播中心,然后向各个收听者发送消息来实现传值。Notification Center是一个单例对象。

    实现方式如下:

    1.设置通知中心:

    static MyNotificationCenter *center;
    
    @implementation MyNotificationCenter
    //用单例模式初始化
    +(MyNotificationCenter *)sharedBoardCast
    {
        if (center == nil) {
            center = [[MyNotificationCenter alloc]init];
        }
        return center;
    }
    -(void)sendMessage
    {
        NSDictionary *dict = @{@"name":@"moxue"};
        //设置当前的通知中心并发送广播
        [[NSNotificationCenter defaultCenter]postNotificationName:@"moxue" object:self userInfo:dict];
    }
    @end

    2.设置收听者

    -(void)getCast
    {
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(cast:) name:@"moxue" object:nil];//注册听众
    }
    -(void)cast:(NSNotification *)notice
    {
        NSLog(@"%@",notice.userInfo);//得到消息后处理事务
    }

    实现:

    MyNotificationCenter *center = [MyNotificationCenter sharedBoardCast];
        [center sendMessage];
        
        Listener *ls = [[Listener alloc]init];
        [ls getCast];

    3.移除通知

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"moxue" object:self];//移除单个通知
    
    [[NSNotificationCenterdefaultCenter] removeObserver:self];//移除当前所有通知
  • 相关阅读:
    GraphX学习笔记——Programming Guide
    GraphX学习笔记——可视化
    Gephi学习笔记
    Ubuntu16.04安装apache-airflow
    Centos7.0下MySQL的安装
    同时安装anaconda2和anaconda3
    Hive学习笔记——安装和内部表CRUD
    Python爬虫学习——布隆过滤器
    Ubuntu下安装和使用zookeeper和kafka
    Ubuntu16.04安装xgboost
  • 原文地址:https://www.cnblogs.com/moxuexiaotong/p/4967053.html
Copyright © 2011-2022 走看看