zoukankan      html  css  js  c++  java
  • iOS通知3种使用方法

    NSNotification 的3种使用方式

    • 1、不传递参数, 最常用的一种
    // 发送通知
    -(void)btn1Click{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"notifyName1" object:nil];
    }
    
    //注册通知(接收,监听,一个通知)
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification1) name:@"notifyName1" object:nil];
    
    //实现方法
    -(void)notification1{
    NSLog(@"接收 不带参数的消息");
    }
    
    • 2、使用object 传递消息
    //发通知
    -(void)btn2Click:(UIButton *)btn{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"notifyName2" object:[NSString stringWithFormat:@"%@",btn.titleLabel.text]];
    }
    
    //注册通知(接收,监听,一个通知)
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification2:) name:@"notifyName2" object:nil];
    
    //实现方法
    -(void)notification2:(NSNotification *)noti{
    
    //使用object处理消息
    NSString *info = [noti object];
    NSLog(@"接收 object传递的消息:%@",info);
    
    }
    
    
    • 3、使用userInfo 传递消息
    //发通知
    
    -(void)btn3Click{
    
    NSDictionary *dic = [NSDictionary dictionaryWithObject:@"userInfo消息" forKey:@"param"];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"nitifyName3" object:nil userInfo:dic];
    
    }
    
    //注册通知(接收,监听,一个通知)
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification3:) name:@"nitifyName3" object:nil];
    
    //实现方法
    -(void)notification3:(NSNotification *)noti{
    
    //使用userInfo处理消息
    NSDictionary  *dic = [noti userInfo];
    NSString *info = [dic objectForKey:@"param"];
    NSLog(@"接收 userInfo传递的消息:%@",info);
    
    }
    
    最后,在[接收]消息的页面,在dealloc方法里面移除观察者。
    
    -(void)dealloc{
    
    //移除观察者
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    }




  • 相关阅读:
    HDU 2201 熊猫阿波问题==金刚坐飞机问题
    HDU 2100 (模拟进制加法)
    HDU 2151 Worm
    qsort快速排序
    HDU 1007 (最近点对+qsort对结构体的排序!!!)
    HDU 1348 wall (简单凸包)
    HDU 1392 Surround the Trees(凸包模板)
    HDU 1431素数回文
    HDU 2108 Shape of HDU(判断拐点)
    HDU 2857 Mirror and Light(镜面反射模板)
  • 原文地址:https://www.cnblogs.com/-ios/p/10608973.html
Copyright © 2011-2022 走看看