我正在为用户输入时给出结果的iPhone创建字典应用程序。我使用线程(NSThread)来更新UITableView,以便主线程不被阻塞。但是,当UITableView询问数据源的行数(tableView:numberOfRowsInSection :)并返回,比如说10时,就会发生崩溃。然后它询问数据源的单元格0-9(tableView:cellForRowAtIndexPath :)。但是当它要求单元7时,数据源已经改变了,现在它只有5行,从而导致崩溃。使用线程更新UITableView
这是我如何解决这个问题:
我在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];
它彻底解决了死机问题。不过,我认为它可能效率不高,因为数据源在每次询问单元时都必须锁定/解锁。而我上面提到的情况并不经常发生。有没有人有更好的想法如何有效地解决这个问题?
非常感谢!
你不应该更新在另一个线程的UI。 – rickharrison 2010-07-30 20:06:45
Rick,我必须在另一个线程中搜索结果,因为搜索方法非常慢,我不希望它阻塞主线程。你能解释一下如何在不使用其他线程的情况下实现这一目标吗? – ifvc 2010-07-30 20:14:52
使它更快。你究竟在寻找什么?! – mvds 2010-07-30 20:17:51