ViewController调用顺序问题,解决ViewController之间传递数据失败的问题
先看下面的代码:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
DetailViewController *detailViewController = [[DetailViewController alloc] init];
detailViewController.nameLabel.text = @"选中的数据";
[self.navigationController pushViewController:detailViewController animated:YES];
}
{
DetailViewController *detailViewController = [[DetailViewController alloc] init];
detailViewController.nameLabel.text = @"选中的数据";
[self.navigationController pushViewController:detailViewController animated:YES];
}
现象:nameLabel 没有能够获取到正确的数据,为什么呢?
=================================================
此时,Controller还没有对View进行装载,导致nameLabel组件其实依然是nil,尽管没有提示错误,却不成功
可以改成下面的代码:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
DetailViewController *detailViewController = [[DetailViewController alloc] init];
[self.navigationController pushViewController:detailViewController animated:YES];
detailViewController.nameLabel.text = @"选中的数据";{
DetailViewController *detailViewController = [[DetailViewController alloc] init];
[self.navigationController pushViewController:detailViewController animated:YES];
}
这样就可以正常运行了。
=================================================
但是从程序语言规范的程度上考虑,不建议直接访问UIViewController内部的组件
在.h文件中声明一个新的NSString对象:
@property (strong, nonatomic) NSString *name;
然后,上面的代码改成:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
DetailViewController *detailViewController = [[DetailViewController alloc] init];
detailViewController.name = @"选中的数据";
[self.navigationController pushViewController:detailViewController animated:YES];
} {
DetailViewController *detailViewController = [[DetailViewController alloc] init];
detailViewController.name = @"选中的数据";
[self.navigationController pushViewController:detailViewController animated:YES];
然后,在viewDidLoad方法中
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.nameLabel.text = _name;
}
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.nameLabel.text = _name;
}
这样,程序的结构更清晰,更有利于代码重构