Ios UITableView在滚动时变慢

Ios UITableView在滚动时变慢,ios,objective-c,uitableview,Ios,Objective C,Uitableview,我有一个UITableView,它在滚动过程中变得非常滞后。 图像保存在JSON的数组中(在viewDidLoad中),CellForRowatineXpath中图像的代码为: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *simpleTableIdentifier = @"UserDiscounts

我有一个UITableView,它在滚动过程中变得非常滞后。 图像保存在JSON的数组中(在viewDidLoad中),CellForRowatineXpath中图像的代码为:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = @"UserDiscountsTableViewCell";

UserDiscountsTableViewCell *cell = (UserDiscountsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];


if (cell == nil) {
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"UserDiscountsTableViewCell" owner:self options:nil];
    cell = [nib objectAtIndex:0];
}


cell.userDiscountNameLabel.text = [userDiscountName objectAtIndex:indexPath.row];

cell.userDiscountImages.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[userDiscountImages objectAtIndex:indexPath.row]]]];


return cell;
}

我正在使用自定义UITableViewCell。当我删除cell.userDiscountImages.image的部分代码时,一切都很正常


有人能告诉你是什么原因导致了延迟滚动吗?

你的表视图延迟了,因为你在加载图像时正在主线程上执行网络代码。请参阅苹果文档:


这个开源库是处理异步映像加载的好方法:

您自己回答了问题:如果您在设置映像时删除了行,一切都正常。这一行需要花费大量的时间来处理,如果您在主线程上进行处理,就会阻塞UI

尝试使用Grand Central Dispatch将图像初始化发送到后台线程。初始化完成后,您需要返回主线程,然后才能进行UI更新。这将看起来像这样:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[userDiscountImages objectAtIndex:indexPath.row]]]];

    dispatch_async(dispatch_get_main_queue(), ^{
        UserDiscountsTableViewCell *discountCell = (UserDiscountsTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        discountCell.userDiscountImages.image = img
    });
});
请注意,在初始化图像后,我不会直接在单元格上设置它,而是从
UITableView
中取回它:这是因为在加载图像时,单元格可能已被重用,以在另一个
nsindepath
中显示另一个单元格。如果您不这样做,您可能会在错误的单元格中得到错误的图像