【问题标题】:Asynchronous image loading in iPhone?iPhone中的异步图像加载?
【发布时间】:2013-06-29 09:41:09
【问题描述】:
您好,我是 iPhone 应用程序的新手。在我的应用程序中,我使用了 tableview。
当我单击表格单元格时,它会显示具有 UIScrollview 的详细视图。我在哪里加载
来自 NSMutableArray 的图像。在那个 NSMutableArray 中有一些 URL 图像。
当我单击表格单元格时,加载所有图像需要更多时间。
请帮助我完成我的申请。很多人说要异步进行
但我不知道该怎么做。
提前致谢。等待解决方案。
【问题讨论】:
标签:
url
asynchronous
uiimage
nsmutablearray
【解决方案1】:
您可能应该使用诸如 AFNetworking 之类的库来加载您的图像,它会处理 tableView 上图像的下载和交换。
【解决方案2】:
首先我想推荐你Paul Hegarty tutorials(在第9、10和主要是第11讲(多线程)中)你可以学到很多东西。
这里有一些示例代码可以帮助您快速但多余:
dispatch_queue_t imageFetchQ = dispatch_queue_create("image fetcher", NULL);
dispatch_async(imageFetchQ, ^{
NSData *imageData = [[NSData alloc] initWithContentsOfURL:self.imageURL]; // could take a while
// UIImage is one of the few UIKit objects which is thread-safe, so we can do this here
UIImage *image = [[UIImage alloc] initWithData:imageData];
// check to make sure we are even still interested in this image (might have touched away)
if (self.imageURL == imageURL) {
// dispatch back to main queue to do UIKit work
dispatch_async(dispatch_get_main_queue(), ^{
if (image) {
self.scrollView.zoomScale = 1.0;
self.scrollView.contentSize = image.size;
self.imageView.image = image;
self.imageView.frame = CGRectMake(0, 0, image.size.width, image.size.height);
}
});
}
});