【发布时间】:2011-06-17 18:50:47
【问题描述】:
我正在使用标准缓存方法来缓存从 Documents 目录加载的一些 UIImages。图像显示在 UITableView 中。它们非常大——图像本身高达 600x600,并以 240x180 的图像视图显示(在视网膜显示器上,因此分辨率差异不大)。
当新单元格即将出现在屏幕上时,实时加载图像会导致一些延迟。所以我在处理图像的对象中实现了一个缓存方法:
- (UIImage *)imageWithStyle:(NSString *)styleName {
NSLog(@"looking for image %@", self.imageFileName);
/* if we have a cached image in dictionary, return it */
if (imageCache == nil) imageCache = [[NSMutableDictionary alloc] init];
UIImage *returnImage = [imageCache objectForKey:styleName];
if (returnImage != nil) {
NSLog(@"returning cached image");
return returnImage;
}
/* otherwise, look for image at path */
NSString *path = [self cacheFilePathWithStyle:styleName];
UIImage * originalImage = [[UIImage alloc] initWithContentsOfFile:path];
/* if image doesnt exist at path, start download and return nil */
if (originalImage == nil) {
NSLog(@"image not found. downloading.");
[self downloadImageFromS3];
return nil;
}
/* found image at path */
/* scale image for screen */
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] && [[UIScreen mainScreen] scale] == 2){
returnImage = [UIImage imageWithCGImage:[[originalImage autorelease] CGImage] scale:2.0 orientation:UIImageOrientationUp];
NSLog(@"scaling image for retina");
} else {
returnImage = [originalImage autorelease];
NSLog(@"image scaled for standard resolution");
}
/* cache image in dictionary */
NSLog(@"caching image");
[imageCache setObject:returnImage forKey:styleName];
return returnImage;
}
在 tableview 出现在屏幕上之前,我强制所有图像处理对象运行此缓存方法,以确保图像存在于字典中,以便在需要显示时检索它们。通过 NSLog,我可以看到一切正常。
我现在获得了无延迟的性能,但只有在图像出现在屏幕上一次之后。因此,当我最初看到 tableview 时,我向下滚动并且 NSLogs 告诉我正在从缓存中检索图像,但我仍然得到相同的加载延迟。一个单元格在屏幕上出现一次后,它就会立即加载。
这里有什么我遗漏的吗?我还需要做些什么来实际缓存图像吗?加载它并将其放入字典似乎并没有解决问题。
谢谢!
更新
我现在已经放弃了。有一些尝试通过在新的上下文中绘制图像来强制加载图像,但我目前还不熟悉核心图形编程。我尝试了一些人们共享的代码,但没有成功。
相反,我将在 tableview 滚动时显示图像的低分辨率版本,并在 tableview 通过其委托方法宣布停止滚动时加载高分辨率版本。至少我知道这种方法适用于任意数量的图像。
【问题讨论】:
标签: caching ios uitableview uiimage