gpt4 book ai didi

iphone - 使用线程更新 UITableView

转载 作者:行者123 更新时间:2023-12-03 18:56:12 25 4
gpt4 key购买 nike

我正在为 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];

彻底解决了崩溃问题。但是,我认为这可能效率不高,因为每次请求单元格时数据源都必须锁定/解锁。而且我上面提到的情况并不经常发生。有谁知道如何有效地解决这个问题?

非常感谢!

最佳答案

不要尝试从后台线程更新 UI。这是行不通的。

关于iphone - 使用线程更新 UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3374979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com