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

来源:互联网 发布:人工智能出现表明 编辑:程序博客网 时间:2024/06/07 09:39
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:vcanimated: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:niluserInfo: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
原创粉丝点击