在从viewController push新的tableViewController时,没有加载数据,是为何?

//在viewController中
- (IBAction)openCardsTable:(id)sender {
    CardsTableViewController *controller = [[CardsTableViewController alloc]init];

    [self.navigationController pushViewController:controller animated:YES];
}

//CardsTableViewVontroller中 -(id)init{ self = [super init]; if(self){ data = [ContactInfoStore defaultStore]; NSLog(@"data array:%@",[data array]); } return self; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 0; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section. NSLog(@"data array:count:%lu",(unsigned long)[[data array] count]); return [[data array]count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"]; if(!cell){ cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cellIdentifier"]; } ContactInfo *item = [data.array objectAtIndex:indexPath.row]; cell.textLabel.font = [UIFont systemFontOfSize:18.0]; cell.detailTextLabel.font = [UIFont systemFontOfSize:13.0]; cell.textLabel.text = item.name; cell.detailTextLabel.text = item.jobDescription; return cell; }

//后面这三个代理方法没有执行,是为何呢?

阅读 5.9k
2 个回答

numberOfSectionsInTableView方法中return 1

首先你要确保你是使用的UITableviewController,如果继承自UIviewController的话,请针对table进行设置两个数据源 (dataSource) 和代理 (delegate);

如果是UITableviewController,请继续阅读

问题猜测起源

个人认为是你的程序在执行顺序中出现了问题,导致data本身没有数据,获知延迟出现数据。

通过断点步骤进行检查

  • 断点在上面的- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section的开始。

  • 如果进入断点,请查看data是否为nil,或者为标准数组。

解决方法

  • data为nil的情况

data为nil的原因是data = [ContactInfoStore defaultStore];异步执行,导致数据晚点到了,那么就需要在defaultStore面调用:[self.tableview reload];//当有数据的时候重新加载。

  • data为标准array的情况

这个的解决我有时候也疑问,当然也是有两种

1.调整代码。
将init中的代码调整到-viewdidload

2.加入代理的代码(这个一般不需要,但是可以尝试)
在viewdidload中加入

    self.tableview.delegate = self;
    self.tableview.dataSource = self;

备注

虽然写了那么多,但是拿不准你的问题,也可能是一个很小的问题,祝好:)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题