相关疑难解决方法(0)

使用线程更新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)

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

非常感谢你!

iphone multithreading cocoa-touch uitableview

5
推荐指数
1
解决办法
5367
查看次数

标签 统计

cocoa-touch ×1

iphone ×1

multithreading ×1

uitableview ×1