我正在为iPhone创建一个字典应用程序,它在用户键入时给出结果。我使用线程(NSThread)来更新UITableView,这样主线程就不会被阻塞。
但是,当UITableView向数据源询问行数时( tableView:numberOfRowsInSection:),我返回,比如说,10。然后它向数据源询问单元格0-9 (tableView:cellForRowAtIndexPath:)。但是,当它请求单元格7时,数据源已经更改,现在只有5行,因此导致崩溃。
下面是我解决这个问题的方法:
我在init方法中创建了一个NSLock。
下面是数据源的外观:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [results count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
[lock lock];
if (indexPath.row < [results count]) {
cell.textLabel.text = [results objectAtIndex:indexPath.row];
}
[lock unlock];
return cell;
}下面是我用来更新表的代码:
[tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];它完全解决了崩溃问题。但是,我认为它可能效率不高,因为每次请求单元格时,数据源都必须锁定/解锁。我上面提到的情况并不经常发生。有没有人有更好的办法有效地解决这个问题?
非常感谢!
发布于 2013-03-18 12:56:23
https://stackoverflow.com/questions/3374979
复制相似问题