Notification传值

接触通知中心很久了,一直也没用过它传值,今天任务完成的比较早,所以做了个小demo,后界面通知中心往前界面传值

 

发送者视图控制器:

- (void)viewDidLoad {

    [super viewDidLoad];

}

- (IBAction)call:(id)sender {

    //当输入框内的文字不为空时

    if (_aTextfield.text) {

        //以输入框的值作为value,以A作为键,存储为字典

        NSDictionary *dics = @{@"A":_aTextfield.text};

        //创建notification对象,name名字为两个控制器通知的唯一标识

        NSNotification *notifications = [[NSNotification alloc] initWithName:@"abc" object:nil userInfo:dics];

        [[NSNotificationCenter defaultCenter]postNotification:notifications];

        [self dismissViewControllerAnimated:YES completion:nil];

    }

}

 

 

 

 接受者视图控制器:

- (void)viewDidLoad {

    [super viewDidLoad];

    //接受者注册通知中心,name字段和发送者相同

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

                                        

}

 

-(void)abc:(NSNotification *)notif {

   _abt.text = notif.userInfo[@"A"];

    NSLog(@"%@",_abt.text);

    

}

注意:dalloc写在创建观察者的控制器里面

- (void)dealloc

{

    //消息发送完,要移除掉

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

}

 

总结:综上所述,通知中心在两个视图控制器关联很少的时候很适合使用,轻量级传值,堪比属性传值

转载于:https://www.cnblogs.com/OC888/p/5515004.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值