在第一个视图控制器的viewWillAppear:中,注册通知 添加观察者来指定一个方法,名称和对象,接受到通知时执行这个指定的方法
复制代码
1
2[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receive:) name:@"send" object:nil];
(注意名字name)
在下面实现这个方法:
复制代码
1
2
3
4
5
6- (void)receive:(NSNotification *)notification { NSDictionary *dict = notification.userInfo; _firstLabel.text = dict[@"first"]; _secondLabel.text = dict[@"second"]; }
查看定义:
复制代码
1
2+ (instancetype)notificationWithName:(NSNotificationName)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;
最后一个参数userInfo一定要是字典。
在第二个视图控制器的返回的方法中,创建通知对象并在通知中心发布通知:
复制代码
1
2
3
4
5
6
7
8
9- (void)back { //创建通知对象 NSNotification *notification = [NSNotification notificationWithName:@"send" object:self userInfo:@{@"first":_firstTextField.text,@"second":_secondTextField.text}]; //注意name //通知中心发布通知 [[NSNotificationCenter defaultCenter] postNotification:notification]; [self dismissViewControllerAnimated:YES completion:nil]; }
最后再回到第一个视图控制器中,移除观察者:
复制代码
1
2
3
4- (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self name:@"send" object:nil]; }
(注意名字name)
上面三个名字注意一定要一致。
最后
以上就是简单狗最近收集整理的关于[iOS开发]通知传值的全部内容,更多相关[iOS开发]通知传值内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复