我遇到了仅在iOS 8上发生过的问题。我使用NSCache
来存储图像。收到内存警告后,我将获取图像并再次存储到缓存中。但是,警告后缓存不再存储我的图像。使用总是会返回nil给我objectForKey:
。
这是我的代码的一部分:
@interface ViewController ()
{
NSCache *imageCache;
}
@implementation ViewController
- (instancetype)init
{
self = [super init];
if (self) {
imageCache = [[NSCache alloc] init];
[imageCache setTotalCostLimit:1024 * 1024 * 1];
}
return self;
}
- (void)imageDownloadManager:(ImageDownloadManager *)manager didReceiveImage:(UIImage *)image forObjectID:(NSString *)objecID
{
NSUInteger cost = [UIImageJPEGRepresentation(image, 0) length];
image = [image smallImageWithCGSize:kImageThumbSize];
[self.imageCache setObject:image forKey:objectID cost:cost];
NSLog("image: %@",[self.imageCache objectForKey:objectID]); //return nil
}
@end
谢谢 :)
解决方案
您必须设置countLimit
并且该值必须大于0。然后您也可以使用totalCostLimit
。
我遇到了同样的问题(并且仅在iOS 8.1下),并且通过分配countLimit而不是totalCostLimit使其工作。
// getter
- (NSCache *)cache
{
if (!_cache) {
_cache = [[NSCache alloc] init];
_cache.countLimit = aLimit;
}
return _cache;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句