通知中心

ViewController

  • (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor redColor];
    //1.通知中心频道必须保持一致
    //2.必须先注册通知中心才能发送通知
    //3.通知中心不是UI控件,所以需要视图控制器被销毁的时候移除

    //添加通知中心
    //参数3:频道
    //参数4:形参
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeValue:) name:@”hello” object:nil];
    }

  • (void)changeValue:(NSNotification *)noti
    {
    NSLog(@”v.userInfo == %@”,noti.userInfo);
    NSLog(@”v.object == %@”,noti.object);
    }

  • (void)touchesBegan:(NSSet )touches withEvent:(UIEvent )event
    {
    ViewController1 *v1 = [[ViewController1 alloc] init];
    [self presentViewController:v1 animated:YES completion:nil];
    }

  • (void)dealloc
    {
    //移除当前视图控制器的指定通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@”hello” object:nil];

    //移除当前视图控制器的所有通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    }

ViewController1

  • (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor orangeColor];
    // Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeValue:) name:@”hello” object:nil];
    }

  • (void)changeValue:(NSNotification *)noti
    {
    NSLog(@”v1.userInfo == %@”,noti.userInfo);
    NSLog(@”v1.object == %@”,noti.object);
    }

  • (void)touchesBegan:(NSSet )touches withEvent:(UIEvent )event
    {
    ViewController2 *v2 = [[ViewController2 alloc] init];
    [self presentViewController:v2 animated:YES completion:nil];
    }

ViewController2

  • (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.view.backgroundColor = [UIColor yellowColor];

}

  • (void)touchesBegan:(NSSet )touches withEvent:(UIEvent )event
    {
    //发送通知
    // [[NSNotificationCenter defaultCenter] postNotificationName:@”hello” object:@”发送消息”];

    //带一个参数
    [[NSNotificationCenter defaultCenter] postNotificationName:@”hello” object:nil];

    NSMutableDictionary *dictM = [NSMutableDictionary dictionaryWithObject:@”1”forKey:@”one”];

    //带两个参数
    [[NSNotificationCenter defaultCenter] postNotificationName:@”hello” object:@”object消息” userInfo:dictM];
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值