zoukankan      html  css  js  c++  java
  • ViewController调用顺序问题,解决ViewController之间传递数据失败的问题

    先看下面的代码:

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        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 = @"选中的数据";

    }

    这样就可以正常运行了。

     =================================================

    但是从程序语言规范的程度上考虑,不建议直接访问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];
    }

    然后,在viewDidLoad方法中

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view from its nib.
        self.nameLabel.text = _name;
    }

    这样,程序的结构更清晰,更有利于代码重构

    下载程序代码

  • 相关阅读:
    hdu 2485 Destroying the bus stations 迭代加深搜索
    hdu 2487 Ugly Windows 模拟
    hdu 2492 Ping pong 线段树
    hdu 1059 Dividing 多重背包
    hdu 3315 My Brute 费用流,费用最小且代价最小
    第四天 下载网络图片显示
    第三天 单元测试和数据库操作
    第二天 布局文件
    第一天 安卓简介
    Android 获取存储空间
  • 原文地址:https://www.cnblogs.com/iihe602/p/2739136.html
Copyright © 2011-2022 走看看