一般在项目中,是很少使用KVC来访问属性的,今天手贱,想玩玩KVC,于是写了下面一段代码
TestViewController *VC = [[TestViewController alloc] init];
//nextTextField是IBOutlet关联出来的
[VC setValue:@"a" forKeyPath:@"nextTextField.text"];
[self presentViewController:VC animated:YES completion:^{
}];
乍一看,没什么问题,但是运行后,跳转到下个控制器时,nextTextField是空的,稍加思考一下,应该是view还没加载出来,此时VC去访问nextTextField,nextTextField是nil
于是我把代码改成下面这个样子,就好了
TestViewController *VC = [[TestViewController alloc] init];
VC.view.backgroundColor = [UIColor grayColor];
[VC setValue:@"a" forKeyPath:@"nextTextField.text"];
[self presentViewController:VC animated:YES completion:^{
}];
运行完VC.view,view加载出来,nextTextField就有了
接着,我在TestViewController中的viewDidLoad方法内重新给VC设置新的颜色
self.view.backgroundColor = [UIColor greenColor];
发现还是上面的grayColor,到这就可以断定,view的加载方式是懒加载,也就是说执行到VC.view时,先懒加载view,同时执行viewDidLoad方法,先给VC设置greenColor,等
VC.view.backgroundColor = [UIColor grayColor];
执行完又被改成了grayColor
当然,即使不用KVC,使用属性传值也是如此
TestViewController *VC = [[TestViewController alloc] init];
VC.view.backgroundColor = [UIColor grayColor];
VC.name = @"abc";
[self presentViewController:VC animated:YES completion:^{
}];
TestViewController中如是
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor greenColor];
_nextTextField.text = _name;
}
nextTextField是不会被赋值的,因为执行完
VC.view.backgroundColor = [UIColor grayColor];
viewDidLoad方法已经执行
网友评论