gpt4 book ai didi

ios - iOS 上的 TableView 异步刷新

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:20:12 24 4
gpt4 key购买 nike

我有一个使用此方法填充的简单 TableViewController:

- (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];
}

dispatch_async(dispatch_get_global_queue(0, 0), ^{

NSInteger row = [indexPath row];
cell.textLabel.text = [[NSString alloc] initWithFormat:@"%d", row];

dispatch_async(dispatch_get_main_queue(), ^{

[cell setNeedsLayout];

});

});

return cell;
}

在第一次加载时,数字显示正确。当我 ScrollView 时,数字随机显示(然后它们被正确排序)。

为什么,滚动,数字没有排序?

enter image description here

最佳答案

UIKit 不是线程安全的。您不能在另一个线程上设置 UIImageView 的图像,同样,您不能在另一个线程上设置 UILabel 的文本。试试这个:

dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSInteger row = [indexPath row];
[cell.textLabel performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:@"%d", row] waitUntilDone:YES];
});

不过,就我个人而言,我完全不明白您为什么要使用 dispatch。从整数创建字符串的开销很小,除非幕后进行的处理比此处显示的更多。

你可以只用这个代替调度调用:

 NSInteger row = [indexPath row];
cell.textLabel.text = [NSString stringWithFormat:@"%i", row];

关于ios - iOS 上的 TableView 异步刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8881935/

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