这里简单说明下IOS页面传值的方法,如有说的不足或者疑虑的地方,欢迎指出说明,本人定修改完善,谢谢大家。
ios的页面传值主要有以下六种方法:
以下演示的是:传一个NSString类型的值至另一个页面。
1、属性传值
A页面:FirstViewControl
.m文件
//创建一个跳转页面的对象
、、、
SecondViewController *secondViewController = [[SecondViewController alloc] init];如果用的storybook而不是xib文件,对应用:SecondViewController *SecondViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondViewControl"];)
、、、
//调用B页面的属性,进行传值
secondViewController.receiveText = @"测试";
//跳转B页面
[self presentViewController:secondViewController animated:YES completion:nil];
B页面: SecondViewControl
.h文件
//定义一个属性
@property (nonatomic , strong) NSString *receiveText;
2、单例传值
//创建一个单例 SingleCase类 继承NSObject
.h文件
//创建一个类方法
+ (SingleCase *) shareInstance;
//创建一个属性
@property (nonatomic,copy) NSString *receiveText;
.m文件
//实现类方法
+ (SingleCase *)shareInstance{
static SingleCase *single = nil;
if (single == nil) {
single = [[SingleCase alloc] init];
}
return single;
}
A页面:FirstViewControl
.m文件
[SingleCase shareInstance].receiveText = @“测试”;
B页面: SecondViewControl
.m文件
3、NSUserDefault传值
[[NSUserDefaults standardUserDefaults] setInteger:value forKey:key];(存值)
[[NSUserDefaults standardUserDefaults] integerForKey:key];(取值)
注意:不可频繁使用,为此开辟的内存,使用后将不会自动删除,除非删除App。
4、协议传值
5、Block传值
.h文件
@property (nonatomic,copy) void (^tickeBlock)(NSString *str);
回传页面
[ticketVC setTickeBlock:^(NSString * _Nonnull str) {
}];