iOS 通知的基本使用传值

本文详细介绍了如何在iOS应用中使用通知中心来发送和接收通知。包括如何通过NSNotificationCenter发送自定义通知,如何注册成为观察者接收特定的通知,并在接收到通知时执行相应的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//设置通知  
 //获取通知中心
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    //通知中心 发送广播
    /*
     第一个参数就是通知的名字 第二个参数 谁发送的通知
        第三个参数 通知的内容
      
     这个方法内部会创建一个通知对象
     */
    //把通知的内容放入字典中
    NSDictionary *dict = @{@"status": @"123"};
     
    //自定义的通知
    [nc postNotificationName:kNotificationChangeStatus object:self userInfo:dict];
 
 
/***********************************************************************************/
//接收通知
//在viewDidLoad方法中注册观察者
//提前创建观察者
        NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
        //注册观察者
        //接收任意对象发送的kNotificationChangeStatus通知
        [nc addObserver:self selector:@selector(changeLabelText:) name:kNotificationChangeStatus object:nil];
 
 
//实现接收通知方法
- (void)changeLabelText:(NSNotification*)nf{
    //获取通知的内容
    NSDictionary *dict = nf.userInfo;
     
    NSString * isOn = dict[@"status"];
     NSLog(@"%@", isOn);
 
}
//最后别忘了 
//删除观察者
- (void)dealloc{
    //删除观察者
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kNotificationChangeStatus object:nil];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值