iOS开发 通知中心传值以及仅通知

    xiaoxiao2021-03-26  17

    利用通知中心传递信息在一个控制器传给上一个控制器的情况经常用到

    不传值时常用于触发某种action:

           在发送方:

    [[NSNotificationCenter defaultCenter]postNotificationName:@"post" object:self];       在接收方:

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(action) name:@"post" object:nil]; 在传值时候

           发送方:

    [[NSNotificationCenter defaultCenter]postNotificationName:@"post" object:self userInfo:@{@"start":_start.text,@"end":_end.text,@"time":_timeTextField.text}];        接收方:

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(action:) name:@"successQuery" object:nil]; 其中action有个“: ”就是传过来的字典,需要解析

    -(void)action:(NSNotification*)notification{ NSDictionary *nameDictionary = [notification userInfo]; seachMsg = (NSMutableDictionary*)nameDictionary; ...... }

    很重要一点

    如果观察者如果对通知没兴趣,也即在接受通知消息的控制器消失时或者不用时,应该移除对通知的观察

    -(void)dealloc{ [[NSNotificationCenter defaultCenter]removeObserver:self]; }或者

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NAME" object:test];//object 与注册时相同

    转载请注明原文地址: https://ju.6miu.com/read-658644.html

    最新回复(0)