我正在使用NSCache
,我正在使用NSCache
存储图像。我正在显示图像UITableView
。每当我首先添加图像时,它们都会调整大小,然后添加到表格中,然后添加到NSCache
. 一切正常。
但是每当我关闭应用程序并再次打开时应用程序进入后台,我的缓存将是空的,我的应用程序会再次调整图像大小然后显示它,因此我首先看到一个空表。
我不明白为什么会这样。这是 的预期行为NSCache
吗?.如果是,那么我们如何改善用户体验,以便使用不会看到滞后。
这是@ipmcc 向我建议的代码
这里的类别是我的实体名称(我正在使用 coreData)
// A shared (i.e. global, but scoped to this function) cache
static NSCache* imageCache = nil;
// The following initializes the cache once, and only once
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
imageCache = [[NSCache alloc] init];
});
// Generate a cache key sufficient to uniquely identify the image we're looking for
NSString* cacheKey = [NSString stringWithFormat: @"%@", category.name];
// Try fetching any existing image for that key from the cache.
UIImage* img = [imageCache objectForKey: cacheKey];
self.imageView.image = img;
// If we don't find a pre-existing one, create one
if (!img)
{
// Your original code for creating a resized image...
UIImage *image1 = [UIImage imageWithData:category.noteImage];
CGSize newSize;
if(image1.size.width == 1080 && image1.size.height == 400)
{
newSize = CGSizeMake(300, 111);
}
dispatch_async(dispatch_get_global_queue(0,0), ^{
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image1 drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
dispatch_async(dispatch_get_main_queue(), ^{
// Now add the newly-created image to the cache
[imageCache setObject: newImage forKey: cacheKey];
self.imageView.image = newImage;
});
});
}