ios - 如何进行多线程以更快地将图像加载到tableView?

标签 ios objective-c cocoa-touch

我正在将图像加载到tableView,每次功能

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

执行后,会出现不同的图片url..

我的问题是加载图像花费了太多时间..

我的代码是..

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.tableView1 = tableView;
    static NSString *simpleTableIdentifier = @"SimpleTableCell";
    SimpleTableCell *cell = (SimpleTableCell *)[tableView1 dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SimpleTableCell" owner:self options:nil];
    cell = [nib objectAtIndex:0];
}

    cell.nameLabel.text = title;

    NSString *imageURL = [NSString stringWithFormat: @"http://www.xyz.com/image1.png];

     cell.thumbnailImageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:fullURL]]];
}
return cell;
}

每次图片网址都会改变,加载每个图片都需要时间..

任何人都可以提出任何解决这个问题的想法吗? 多线程如何处理这段代码? 我应该在代码中编辑什么位置?

最佳答案

您必须下载背景图像,例如:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 static NSString *simpleTableIdentifier = @"SimpleTableCell";
    SimpleTableCell *cell = (SimpleTableCell *)[tableView1 dequeueReusableCellWithIdentifier:simpleTableIdentifier];   
         dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,  0ul);
        dispatch_async(queue, ^{

            NSString *u=[NSString stringWithContentsOfFile:r.url encoding:NSUTF8StringEncoding error:nil];
            NSURL *imageURL=[NSURL URLWithString:u];
            NSData *imageData=[NSData dataWithContentsOfURL:imageURL];
            dispatch_sync(dispatch_get_main_queue(), ^{
                SimpleTableCell *cell = (SimpleTableCell *)[tableView cellForRowAtIndexPath:indexPath];
                 cell.thumbnailImageView.image=[UIImage imageWithData:imageData];
                [cell setNeedsLayout];

            });
        });

    }

    return cell;
}

只需在 TableView 方法中使用上面的代码并进行所需的编辑,这应该适合您。

关于ios - 如何进行多线程以更快地将图像加载到tableView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15270395/

相关文章:

html - 如何解决 iPhone 的 Bootstrap 复选框布局问题

ios - __destroy_helper_block_ 上的 Objective-C 崩溃

iOS : View height is getting reduced when performing animation

ios - 您的二进制文件未针对 iPhone 5 进行优化

ios - "Failed to receive system gesture state notification before next touch"

ios - XCode 性能测量

iphone - 使用数组填充 TableView 的正确方法?

ios - 如何在 subview Controller 中更改 iOS 状态栏颜色

ios - 使用 canDisplayBannerAds 时设置委托(delegate)

objective-c - 使用 UIPinchGestureRecognizer 缩放整个屏幕