iOS多视图传值方式之通知传值(NSNotification;NSNotificationCenter)

  • iOS传值方式之5:通知传值

  • 第一需要发布的消息,再创建NSNotification通知对象,然后通过NSNotificationCenter通知中心发布消息(NSNotificationCenter单例)

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

{

    // 创建需要传递的参数

    NSDictionary *dic = @{

                          @"name":@"coputer",

                          @"message":@"using"

                          };

    

    // 创建通知

    NSNotification *note = [NSNotification notificationWithName:@"tongzhi" object:nil userInfo:dic];

    

    // 通过通知中心发送消息:Xcode的单例

    [[NSNotificationCenter defaultCenter] postNotification:note];

    

    // 推到下一页:即接收通知的对象(使用的是模态视图)

    [self presentViewController:[PPFViewController new] animated:YES completion:nil];

 

}

 


 

  • 在发送通知后,在所要接收的控制器中注册通知监听者,将通知发送的信息接收
  • 接收通知也有三步:首先需要注册通知,

- (void)viewDidLoad

{

    [super viewDidLoad];

      // 注册通知

       [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reserve:) name:@"tongzhi" object:nil];

}

 

// 反馈通知:打印通知内容

- (void)reserve:(NSNotification *)messgae

{

    NSLog(@"收到通知");

    NSLog(@"%@", messgae.userInfo);  //形参是NSNotification类型对象指针,因此可以访问其属性

}

 

// 移除通知

- (void)dealloc

{

// ARC可以重写dealloc但不能写[super dealloc]; 因为是自动内存管理

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"tongzhi" object:nil];

}


  • 注意:

其中,removeObserver:是删除通知中心保存的调度表一个观察者的所有入口,

而removeObserver:name:object:是删除匹配了通知中心保存的调度表中观察者的一个入口。

 

注意参数notificationObserver为要删除的观察者,一定不能置为nil。

 

 

转载于:https://www.cnblogs.com/pruple/p/5281051.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值