在ios sdk中加载文档目录中的图像

use*_*811 0 iphone multithreading image ios uicollectionview

我实现了集合视图,我在其中显示文档目录中的图像.

但是由于图像从文档加载,集合视图不能平滑滚动.

如果图像从主束加载,那么它可以正常工作.

我的代码如下:

UIImageView *img=[[UIImageView alloc]init];
img.image=[UIImage imageWithContentsOfFile:[[arr_images objectAtIndex:indexPath.row]valueForKey:@"Image_path"]];
img.contentMode=UIViewContentModeScaleAspectFit;
cell.backgroundView=img;
Run Code Online (Sandbox Code Playgroud)

我应该使用线程吗?如果是的话,我该怎么做?我怎么解决这个?

Abh*_*ert 6

无需使用线程.偶尔加载图像很好,问题是你不断加载图像.

从主捆绑加载可能正常,因为NSBundle正在为您缓存图像.你可以使用NSCache自己做同样的事情.

所以不是这样的:

img.image=[UIImage imageWithContentsOfFile:[[arr_images objectAtIndex:indexPath.row]valueForKey:@"Image_path"]];
Run Code Online (Sandbox Code Playgroud)

做类似的事情:

static NSCache *cache = nil;
if (!cache) {
    cache = [[NSCache alloc] init];
    [cache setCountLimit:10]; // check how much RAM your app is using and tweak this as necessary. Too high uses too much RAM, too low will hurt scrolling performance.
}

NSString *path = [[arr_images objectAtIndex:indexPath.row]valueForKey:@"Image_path"];
if ([cache objectForKey:path]) {
    img.image=[cache objectForKey:path];
} else {
    img.image=[UIImage imageWithContentsOfFile:path];
    [cache setObject:img.image forKey:path];
}
Run Code Online (Sandbox Code Playgroud)

如果你最终发现需要使用线程,那么我会使用GCD线程加载图像,但是然后将该图像插入到我在示例代码中创建的同一个NSCache对象中.基本上使用后台线程来尝试预测哪些图像需要预加载,但允许NSCache决定在销毁这些图像之前将这些图像保留多长时间.