iOS ViewController之间传值方法三(利用NSNotification)

3. 利用NSNotification在两个或多个ViewController之间传值
在A页面

    //注册通知

    [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(click:)name:@"mynotification"object:nil];


    UIButton *jumpBtn = [[UIButtonalloc]initWithFrame:CGRectMake(50,100, 200, 50)];

    jumpBtn.backgroundColor = [UIColorredColor];

    [jumpBtn setTitle:@"click..."forState:UIControlStateNormal];

    [jumpBtn addTarget:selfaction:@selector(clickBtn)forControlEvents:UIControlEventTouchUpInside];

    [self.viewaddSubview:jumpBtn];

    

------------------------------------------------------

-(void)click:(NSNotification*)text{

    NSString *str = text.userInfo[@"1"];

    NSLog(@"---------------%@",str);

}

-(void)clickBtn{

    //PS:UIViewController 跳转方法有两种,1.利用UIViewController自身的presentModalViewController,进行跳转;调用dismissModalViewControllerAnimated方法可以返回。2.利用UINavigationController,调用pushViewController,进行跳转;这种采用压栈和出栈的方式,进行Controller的管理。调用popViewControllerAnimated方法可以返回.

    TwoViewController *vc = [[TwoViewControlleralloc]init];

    [selfpresentViewController:vc animated:YEScompletion:nil];


// Or   [self.navigationController pushViewController:vc animated:YES];

}


  在B页面

    NSDictionary *dic = [[NSDictionaryalloc]initWithObjectsAndKeys:@"this",@"1",@"is",@"2",@"a",@"3",@"dictionary",@"4",nil];

    //创建通知

    NSNotification *myNotification = [NSNotificationnotificationWithName:@"mynotification"object:nil userInfo:dic];

    //通过通知中心发送通知

    [[NSNotificationCenterdefaultCenter]postNotification:myNotification];


个人理解,在A页面要先注册通知才能接收到B页面传过来的值。通知注册就好像初始化一样,如果在A页面直接创建通知,在B页面再注册是无法传值的。

移除通知:removeObserver:和removeObserver:name:object:

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

这个比较简单,直接调用该方法就行。例如:

[[NSNotificationCenter defaultCenter] removeObserver:observer name:nil object:self];

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





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值