我有一个由NSArray支持的UITableView。
- (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将同步请求numberOfSections和numberOfRows,但将异步调用cellForRow。所以有时候,当cellForRowAtIndexPath被调用的时候,数据数组已经改变了,所以[self.data objectAtIndex:indexPath.row]会得到一个越界异常并使应用程序崩溃。我该如何避免这种情况?
请注意,每次设置data数组时,我也会调用[self.tableView reloadData]。
发布于 2012-10-18 07:52:07
cellForRowAtIndexPath被频繁调用(在滚动等),您只需添加一行简单的代码来检查数据数组的大小是否小于所请求的单元格。虽然这意味着你可能会得到空白的单元格。
我在两种方法上都设置了断点,右键单击断点->“编辑断点”并勾选“计算后自动继续”。然后单击"add action“-> "debugger command”,然后键入"po data“或"po data count”。
这将在每次命中断点时在调试控制台中打印有关数组的信息(不会停止)。然后,您应该能够查看调试输出,并查看它不同步的位置。添加一些NSLog语句,以告诉您正在调用哪个方法,等等,并从那里开始工作。
发布于 2012-10-18 13:17:01
我认为避免这种情况的最好方法是在数据更新时避免用户交互,因为您可以向用户显示一个屏幕,即“updated.May ..”和活动指示器。
另一种方式是让另一个数组填充新数据,处理可以在单独的线程中完成,并且有时只有它在that.There之后通过重新加载调用被分配回数据源数组。当数据源数组发生变化时,也可以使用具有相同的屏幕
发布于 2012-10-18 16:34:46
我用过的快速技巧,试试这个,看看它对你是否有效:
- (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
https://stackoverflow.com/questions/12945050
复制相似问题