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