NSCache objectForKey: always return nil after memory warning on iOS 8

1.6k Views Asked by At

I came across a problem that only happened on iOS 8. I used the NSCache to store my images. After receiving memory warning, I would fetch images and store into cache again. However the cache can't store my images anymore after warning. It always returns nil to me by 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

Thanks :)

SOLUTIONS

You have to set countLimit and the value must greater than 0. Then you could use totalCostLimit as well.

1

There are 1 best solutions below

0
On BEST ANSWER

I experienced the same problem (and only under iOS 8.1) and got it working by assigning a countLimit instead of a totalCostLimit.

// getter
- (NSCache *)cache
{
   if (!_cache) {
      _cache = [[NSCache alloc] init];
      _cache.countLimit = aLimit;
   }
   return _cache;
}