【问题标题】:Application crashing when returning 1 row in tableview在 tableview 中返回 1 行时应用程序崩溃
【发布时间】:2016-01-10 00:35:20
【问题描述】:

我有一个表格视图,其中填充了一个名为 json 的数组。如果 json 的长度为 0,我想在我的 tableview 中返回 1 行。

 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  TableViewCell *cell = [self->tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
  NSDictionary *info = [json objectAtIndex:indexPath.row];
  //content is the name of label in the custom cell
  if ([json count]>0) {
    cell.content.text = [info objectForKey:@"message_text"];
  }
  else
    cell.content.text = @"There are currently no messages. Please pull down to refresh";

  return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if([json count]>0)
    return [json count];
else
    return 1;

}

上面的代码导致我的应用程序崩溃,我不确定原因。为什么这不起作用,我该如何解决这个问题。 我收到以下错误:

* 由于未捕获的异常 'NSRangeException' 导致应用程序终止,原因:'* -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray'

【问题讨论】:

  • 请发布您的cellForRowAtIndexPath 方法
  • 我添加了 cellForRowAtIndexPath 方法@Andrew

标签: objective-c uitableview


【解决方案1】:

更改此代码:

NSDictionary *info = [json objectAtIndex:indexPath.row];
//content is the name of label in the custom cell
if ([json count]>0) {
  cell.content.text = [info objectForKey:@"message_text"];
}
else
   cell.content.text = @"There are currently no messages. Please pull down to refresh";

收件人:

//content is the name of label in the custom cell
if ([json count]>0) {
  NSDictionary *info = [json objectAtIndex:indexPath.row];
  cell.content.text = [info objectForKey:@"message_text"];
}
else
   cell.content.text = @"There are currently no messages. Please pull down to refresh";

希望对您有所帮助!

【讨论】:

  • 是的。非常感谢。只是出于好奇,为什么会出现问题以及您提供的代码为什么有效。我只是想理解它。
  • 您在检查代码之外获得了项目。当没有项目超出范围时,它会崩溃。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-17
  • 2012-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-29
  • 1970-01-01
相关资源
最近更新 更多