常见的6种传值方式
1.属性传值 2.方法传值 3.代理传值 4.Block传值 5.单例传值 6.通知传值
1.属性传值
1.传值第一步就得确定传的属性类型,然后就定义什么样的属性
2.在控制器跳转中给属性赋值
TwoViewController *two = [[TwoViewController alloc]init];
two.firstValue = @"ValueToSend";
[self.navigationController pushViewController:two animated:YES];
2.方法传值
方法传值,可以直接将方法与初始化方法合并。
触发MainViewController的点击事件并跳转时,直接通过初始化将值保存。
-(id)initWithValue:(NSString *)value
{
if (self = [super initWithNibName:nil bundle:nil]) {
self.firstValue = value;
}
return self;
}
3.代理传值
这种传值主要用于A进入B,然后B输入值后传回给A。
常见于修改个人信息,点击进入修改界面,修改完之后回到显示界面,显示修改后的结果。
SixViewController *six = [[SixViewController alloc]init];
six.delegate = self;//把自己设置为对方的代理
[self.navigationController pushViewController:six animated:YES];
[self.delegate changeValue:self.DMTextField.text];//对方要做事,让自己去做,就改了自己这边的值
[self.navigationController popViewControllerAnimated:YES];
4.Block传值
闭包特性,传函数过去。
对方之行到这个函数的时候,修改值,就把数值传过来。
EightViewController *eight = [[EightViewController alloc]initWithBlock:^(UIColor *color, NSString *name) {
self.view.backgroundColor = color;
self.DMlabel.text = name;
}];
[self.navigationController pushViewController:eight animated:YES];
NSArray *array = [NSArray arrayWithObjects:[UIColor yellowColor],[UIColor cyanColor],[UIColor greenColor],[UIColor brownColor], nil];
self.myBlock([array objectAtIndex:rand() % 4],_DMTextField.text);
[self.navigationController popViewControllerAnimated:YES];
5.单例传值
写个单例。
+ (AppData *)share {
static AppData *sharedManager =nil;
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
sharedManager = [[self alloc] init];
});
return sharedManager;
}
到处取值。
[AppData share].height = 22;
6.通知传值
(NSNotification *)notification.userInfo可以传NSDictionary.
注册接收通知。
TwelveViewController *twelve = [[TwelveViewController alloc]init];
[self.navigationController pushViewController:twelve animated:YES];
//注册接收通知中心
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
//接收通知
[center addObserver:self selector:@selector(receiveNotification:) name:@"notification" object:nil];
发送通知和数据。
NSArray *array = [NSArray arrayWithObjects:[UIColor greenColor],[UIColor yellowColor],[UIColor cyanColor],[UIColor purpleColor], nil];
_dic = @{@"color":[array objectAtIndex:rand() % 4],
@"text": self.DMTextField.text};
//注册通知中心
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
//发送通知
[center postNotificationName:@"notification" object:@"wangdeming" userInfo:_dic];
接收通知里的数据。
self.view.backgroundColor = [notification.userInfo valueForKey:@"color"];
self.DMTextField.text = [notification.userInfo valueForKey:@"text"];
NSLog(@"%@",notification.object);