控制器A通过连线可以跳转至控制器B,假如控制器B有一个属性name,此时在A跳转到B之前给控制器B赋值:
控制器A的实现文件:
#import "ViewControllerA.h"
#import "ViewControllerB.h"
@interface ViewControllerA ()
@end
@implementation ViewControllerA
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
ViewControllerB *vcB=[[ViewControllerB alloc]init];
vcB.name=@"vcB";
}
@end
控制器B的实现文件:
#import "ViewControllerB.h"
@interface ViewControllerB ()
@end
@implementation ViewControllerB
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"name:%@",self.name);
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
打印结果为:
2017-04-02 18:40:41.461 StoryBoard中控制器跳转注意事项[86405:9255908] name:(null)
说明给控制器B的name属性赋值不成功,这是为什么呢?问题就出在这一句代码ViewControllerB *vcB=[[ViewControllerBalloc]init],来看看下面这一张图吧。
在控制器A跳转B时,系统为自动为你创建一个控制器B的实例对象,它的name属性为空。我们又在跳转之前使用ViewControllerB *vcB=[[ViewControllerB alloc]init]创建了一个控制器B的实例对象,这个vcB对象并不是之前那个对象,这两个对象毫无关系,所以给vcB的属性赋值是没用的。
应该改成这样:
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
ViewControllerB *vcB=segue.destinationViewController;
vcB.name=@"vcB";
}
此时segue的目标控制器对象才是跳转时创建的控制器对象B.
打印结果:
2017-04-02 19:08:56.852 StoryBoard中控制器跳转注意事项[86845:9273295] name:vcB
ps:使用代码块逆向传值时,需要给控制器的代码块属性赋值,此时要注意到这种情况。当然也可以不使用StoryBoard,而直接使用xib或者纯代码进行跳转就可以避免这种情况的出现。
ViewControllerB *vcB=[[ViewControllerB alloc]initWithNibName:@"ViewControllerB" bundle:[NSBundle mainBundle]];
vcB.name=@“vcB”;
[self.navigationController pushViewController:vcB animated:YES];