首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UITableView数据不一致

UITableView数据不一致
EN

Stack Overflow用户
提问于 2012-10-18 07:38:06
回答 4查看 565关注 0票数 0

我有一个由NSArray支持的UITableView

代码语言:javascript
复制
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
  return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  return self.data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *CellIdentifier = @"CellIdentifier";
  UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:CellIdentifier];
  if (cell == nil) {
      cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];

  }
  id item = [self.data objectAtIndex:indexPath.row];
  cell.item = item;

  return cell;
}

非常标准。现在的问题是,reloadData将同步请求numberOfSectionsnumberOfRows,但将异步调用cellForRow。所以有时候,当cellForRowAtIndexPath被调用的时候,数据数组已经改变了,所以[self.data objectAtIndex:indexPath.row]会得到一个越界异常并使应用程序崩溃。我该如何避免这种情况?

请注意,每次设置data数组时,我也会调用[self.tableView reloadData]

EN

回答 4

Stack Overflow用户

发布于 2012-10-18 07:52:07

cellForRowAtIndexPath被频繁调用(在滚动等),您只需添加一行简单的代码来检查数据数组的大小是否小于所请求的单元格。虽然这意味着你可能会得到空白的单元格。

我在两种方法上都设置了断点,右键单击断点->“编辑断点”并勾选“计算后自动继续”。然后单击"add action“-> "debugger command”,然后键入"po data“或"po data count”。

这将在每次命中断点时在调试控制台中打印有关数组的信息(不会停止)。然后,您应该能够查看调试输出,并查看它不同步的位置。添加一些NSLog语句,以告诉您正在调用哪个方法,等等,并从那里开始工作。

票数 0
EN

Stack Overflow用户

发布于 2012-10-18 13:17:01

我认为避免这种情况的最好方法是在数据更新时避免用户交互,因为您可以向用户显示一个屏幕,即“updated.May ..”和活动指示器。

另一种方式是让另一个数组填充新数据,处理可以在单独的线程中完成,并且有时只有它在that.There之后通过重新加载调用被分配回数据源数组。当数据源数组发生变化时,也可以使用具有相同的屏幕

票数 0
EN

Stack Overflow用户

发布于 2012-10-18 16:34:46

我用过的快速技巧,试试这个,看看它对你是否有效:

代码语言:javascript
复制
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *CellIdentifier = @"CellIdentifier";
  UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:CellIdentifier];
  if (cell == nil) {
      cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];

  }

  // -----------------------------------------------------------------
  // the magical line that prevents the table from fetching the data
  // -----------------------------------------------------------------
  if([indexPath row] < [self.data count])
  {

      id item = [self.data objectAtIndex:indexPath.row];
      cell.item = item;
  }

  return cell;
}

:D

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12945050

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档