NSCache objectForKey: always return null after memory warning on iOS 8
I ran into an issue that only happened in iOS 8. I used NSCache
to store my images. After getting the memory warning, I get the images again and store them in the cache. However, after the warning, the cache cannot save my images. It always returns nil to me using objectForKey:
.
Here's part of my code:
@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
Thank:)
SOLUTIONS
You must set countLimit
and the value must be greater than 0. Then you can use totalCostLimit
.
+3
source to share