您的位置:首页 > 移动开发 > IOS开发

iOS关于系统原生通知的实现

2016-06-24 14:10 411 查看
1.设置通知中心 

 //通知中心
单例  (整个工程中只能有一个通知中心)

   

   NSNotificationCenter * center =  [NSNotificationCenter defaultCenter];

   
//    NSNotificationCenter * center2 = [[NSNotificationCenter alloc]init];
//    
//    NSLog(@"-----%@ , ======%@",center,center2);

   

    //发通知

   

    //NO1.   通知名字

    //NO2.   通知是谁发的  一般写self

    //NO3.   用户信息 传值的

    [center postNotificationName:@"changeColor" object:self userInfo:@{@"color":
color}];

2. 在需要监听通知的视图中

  //监听通知

   

    //1. 先找到通知中心

   

    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];

   

    //2.监听通知

    //NO1. Observer  观察者  监听者  self

    //NO2.  selector  监听到通知后
调用的方法

    //NO3.  监听到通知的名字  如果写 nil 
会监听所有的通知

    //NO4.  指定监听到通知的来源 ,如果来源不对 
也是不能监听的  一般写nil

   

    //self 监听  object 发送的名字作为changeColor 的通知 
接到通知后 调用 receiveNotification: 方法

    [center addObserver:self selector:@selector(receiveNotification:) name:@"changeColor" object:nil];

//监听通知绑定的方法  带参数  是将接收的通知本身传过来 

-(void)receiveNotification: (NSNotification *)notification

{
//获取  信息

    NSDictionary * dic = notification .userInfo;

然后可以在字典中或取监听到的内容

eg:

   self .view .backgroundColor =
[dic objectForKey:@"color"];

}

//在手动管理内存时  为防止 监听对象已经release  而通知中心仍然在给监听对象发通知 
造成错误  需要监听对象在销毁之前 移除监听对象  即在监听对象所在的类中调dealloc方法 eg:

-(void)dealloc

{

    [[NSNotificationCenter defaultCenter]removeObserver:self];

    [super dealloc];

}

//批注:
//通知的实现原理 : 在通知中心 
每一个通知的下边都有一个调度列表  ,调度列表中存放的是该通知的所有监听者 
一旦发送通知  通知中心 
就会让调度列表中的每一个对象  去调用他们相应的方法 从而是实现一对多的机制

//过渡释放的原因 :  如果一个监听者要销毁了 而此时  通知中心并不知道该监听者已经被销毁
当发送通知时 会仍然让该监听者去调用相应的方法 这时  程序就会崩溃  发生内存问题 . 所以如果一个监听对象将要销毁之前 需要去通知中心移除监听
,将其从调度列表中删除

//需要在dealloc 方法中移除监听  否则程序就会崩溃

//批注2:

 /*

     通知和代理都是OC中的一种回调机制 , 都可以实现值的反向传递

   

    区别: 1. 代理,  是一对一的  通知是一对多的 代理里面的协议方法 协议方法是可以有返回值的  (eg:  告       诉tableView 每一区有多少行).  监听到通知后绑定的方法
是不需要有返回值的

   

              2.  代理 ,定义协议方法的类和实现协议方法的类之间必须建立联系  实现协议方法中 必须包含定义协议方法的类的对象 (eg :  viewController中必须创建tableView 才能使用协议方法 );

   

                   通知 ,  两个类之间不需要建立任何的联系 ,

   

   

   

   

   

    */

延伸补充 : 如果在name出写空的话  会监听到系统的一些通知  可以再name位置调用系统的一些通知

eg:

  //监听应用程序已经进入后台时系统的通知

   // [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveApplicationDidEnterBackgound:) name:UIApplicationDidEnterBackgroundNotification
object:nil];

   

    //监听键盘frame 将要发生变化时的通知

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveKeyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];

//监听到应用程序已经进入后台时调用的方法

-(void)receiveApplicationDidEnterBackgound: (NSNotification *)notification

{

  //  NSLog(@"name -- %@",notification .name);

   

}
//监听键盘frame发生变化的通知  调用的方法

-(void)receiveKeyboardWillChangeFrame: (NSNotification *)notification

{

    NSLog(@"--------%@",notification.userInfo);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios开发