通知传值
通知传值也是逆向传值的一种,通知中心传值,可以跨越多个页面传值, 一般也是从后面的页面传给前面的页面。
基本步骤
这里的使用背景:在第一个界面有三个数组分别存储姓名班级和成绩,显示在视图上,在第二个界面通过搜索学生姓名删除信息,将新的数组传给第一个界面,重新显示在视图上。
注册通知
在第一个界面跳转到第二个界面时,注册通知中心。
复制代码
1
2
3
4
5
6
7
8
9
10- (void) pressDelChange { DeleteViewController* deleteViewController = [[DeleteViewController alloc] init]; deleteViewController.modalPresentationStyle = UIModalPresentationFullScreen; deleteViewController.homeNameArray = _homeNameArray; deleteViewController.homeMarkArray = _homeMarkArray; deleteViewController.homeClassArray = _homeClassArray; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ChangeArray:) name:@"ChangeArray" object:nil]; [self presentViewController:deleteViewController animated:YES completion:nil]; }
这里要注意消息中心的姓名要和发送消息时的一直,不然会出现无法接受消息的问题,导致数组为空。
在第二个界面发送消息通知
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否删除该学生信息" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { [self.homeNameArray removeObjectAtIndex:i]; [self.homeClassArray removeObjectAtIndex:i]; [self.homeMarkArray removeObjectAtIndex:i]; NSDictionary *diction = [[NSDictionary alloc]initWithObjectsAndKeys:self.homeNameArray,@"Array",self.homeClassArray,@"classArray",self.homeMarkArray, @"markArray", nil]; NSLog(@"%@", diction[@"markArray"]); [[NSNotificationCenter defaultCenter]postNotificationName:@"ChangeArray" object:nil userInfo:diction]; [self dismissViewControllerAnimated:YES completion:nil]; }]; UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]; [alertController addAction:sureAction]; [alertController addAction:cancelAction]; [self presentViewController:alertController animated:YES completion:nil]; return;
这里代码中使用了一个字典存储将要传递的数组,通过键来识别是哪一个。
实现通知中心内部的方法
所谓通知中心的方法,就是注册通知时的第二个参数。在这个方法里实现传值,并充值tableView
复制代码
1
2
3
4
5
6
7
8
9- (void) ChangeArray:(NSNotification *)notification { NSDictionary *dict = notification.userInfo; self.homeNameArray = dict[@"Array"]; self.homeClassArray = dict[@"classArray"]; self.homeMarkArray = dict[@"markArray"]; NSLog(@"%ld", self.homeMarkArray.count); [self.tableView reloadData]; }
移除掉通知中心
复制代码
1
2
3
4
5
6- (void)dealloc{ [[NSNotificationCenter defaultCenter]removeObserver:self]; }
最后
以上就是美满草莓最近收集整理的关于iOS——通知传值通知传值基本步骤的全部内容,更多相关iOS——通知传值通知传值基本步骤内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复