首先声明反向传值有很多种,适合你的项目就是最好的。本博客一直更新
就是在二个界面把值传给单例,然后在第一个界面获取单例值
反向传值方式:
1.单例传值(可以和通知中心配合使用,看自己项目需求)
UIAPPlication单例传值(自定义传值)
第一步
#import "AppDelegate.h"文件中添加自定义的全局变量
@property (nonatomic,strong) NSString *string;
第二步
在第一个界面直接上代码
//界面将要显示的时候
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
//将要显示的时候 从单例中获取值
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//修改值
userPhone = appDelegate.string;
}
第三步
还是直接上代码
-(void)loginBtnAction:(UIButton *)sender{
[self updateData];
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//传值 把值 赋给appDelegate的属性
appDelegate.string = self.userTextField.text;
第二种通知中心反向传值
第一步在接受通知的ViewController注册通知
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test) name:@"test" object:nil];
}
第二步实现通知方法
- (void)test:(id)sender
{
NSLog(@"接受通知");
}
第三步在NavigationController进入的界面发出通知,可以sender打印出来的是那个值得指针地址
- (void)didButtonClicked:(id)sender
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:nil];
}
第三种反向传值观察者监听方式,由A界面跳B界面,拿到B界面数据返回A界面显示出来数据
使用的是模态视图,不能像代理那样使用按钮触发响应,因为模态视图返回后就被销毁了,然而观察者还在,那样内存会出现错误
第一步在A界面ViewDidLoad中定义一个观察者
//a) 初始化模态视图
_modalViewController = [[ModalViewController alloc] init];
//b) 给模态视图定义一个观察者
[_modalViewController addObserver:self forKeyPath:@"textLabel" options:NSKeyValueObservingOptionNew context:nil];
第二步在B界面定义一个观察者公共属性,观察值的变化
@property(nonatomic, copy) NSString *textLabel;
第三步修改Button里面的响应方法
//1) 取值
UITextField *textField = (UITextField *)[self.view viewWithTag:2000];
//2) 修改值
self.textLabel = textField.text;
//3) 关闭模态视图
[self dismissViewControllerAnimated:YES completion:nil];
第四步回到A界面,显示数据
#pragma mark - 观察者响应
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
//1) 获取值得变化
NSString *text = [change objectForKey:@"new"];
//2) 通过tage获取label
UILabel *label = (UILabel *) [self.view viewWithTag:1000];
//3) 改变label的值
label.text = text;}
第五步移除观察者
- (void) dealloc {
[_modalViewController removeObserver:self forKeyPath:@"textLabel"];
}
第四种定义代理实现委托行为