使用线程更新UITableView

ifv*_*fvc 5 iphone multithreading cocoa-touch uitableview

我正在为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;
}
Run Code Online (Sandbox Code Playgroud)

这是我用来更新表的代码:

[tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
Run Code Online (Sandbox Code Playgroud)

它完全解决了崩溃问题.但是,我认为它可能效率不高,因为每次要求一个单元格时,数据源都必须锁定/解锁.我上面提到的情况并不经常发生.有没有人更好地了解如何有效地解决这个问题?

非常感谢你!

mvd*_*vds 2

为什么要为此使用单独的线程?搜索需要多长时间?0.1秒?与用户停止打字并查看屏幕所花费的时间相比如何?

不要让事情过于复杂化!(如果您的搜索时间超过 0.7 秒且无法优化,我将收回此信息;-)