缓存UIImage的最佳方法不是来自网络

时间:2014-02-20 21:05:33

标签: ios objective-c nscache

嗨我在本地(文档)中有高分辨率图像。现在我想列出拇指指甲大小的所有本地图像。我正在使用UICollectionView显示图像,同时加载图像从高分辨率调整大小到缩略图。所以在collectionView中滚动速度不足。现在我对如何缓存调整大小的缩略图图像感到困惑。哪一个是最好的选择。我使用SDWebimages从网上下载和缓存图像。谢谢

 - (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath
    {

    //    NSLog(@"%i path", indexPath.row);
        CollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"CollectionViewCell" forIndexPath:indexPath];
        ImageData *imgData =  [self readFromLocal:indexpath.item];
        UIImage *thumb = [self resizeImgToTumb:imgData.image];
        [cell.imgView setimage:thumg];

return cell;
}

2 个答案:

答案 0 :(得分:1)

我建议将图像存储在特定于应用程序的存储中的文件系统上,并在必要时读取这些文件。使用NSFileManager类来完成此任务。请务必编写代码来清理您创建的任何文件,以免在用户设备上占用太多空间。

UIImage *image = ...;
NSData *imageData = UIImagePNGRepresentation(image);
NSString *rootDirectory = [NSSearchPathForDirectoriesInDomain(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *imagePath = [rootDirectory stringByAppendingPathComponent:@"filename.png"];
NSError *error;

[imageData writeToFile:imagePath options:NSDataWritingAtomic error:&error];

答案 1 :(得分:0)

如果您并不完全担心内存消耗,可以创建一个NSDictionary并将调整后的图像添加到其中。一旦它们离屏幕足够远,您将需要从字典中删除它们,以便稍后重新加载。

[dictionary setObject:yourSmallImage forKey:indexPath];

然后再检索它:

UIImage *image = [dictionary objectForKey:indexPath];
if(!image)
{
    //Load it from your source, no cache found
}