Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSCache: Always getting "not key value coding-compliant" when trying to access cached item

I'm attempting to use NSCache to store PNGs as NSData. Whenever I try to get one back out of the cache, whether the cache is empty or not, I get:

2012-10-26 09:49:28.860 SledMap[55917:11503] * Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ valueForUndefinedKey:]: this class is not key value coding-compliant for the key 0_0_5.'

If I leave the code exactly as is, but change NSCache to NSMutableDictionary, it works fine.

I declare my cache:

@property (nonatomic, strong) NSCache *tileCache;

Allocate it (in viewDidLoad):

self.tileCache = [[NSCache alloc] init];
self.tileCache.delegate = self;

Add something to the cache:

NSString *key = [NSString stringWithFormat:@"%i_%i_%i",x,y,endLevel];
NSData *pngData = [NSData dataWithData:UIImagePNGRepresentation(image)];
[self.tileCache setObject:pngData forKey:key];

And then when I get it back out, I get the above error.

NSString *key = [NSString stringWithFormat:@"%i_%i_%i",x,y,endLevel];
NSData *tile = [self.tileCache valueForKey:key];  //This is the line it crashes on

If it was empty, I would expect it to just return nil, which is what happens when I make self.tileCache an NSMutableDictionary instead of an NSCache. Also, in the debug area, it says:

tile = NSData * 0x0134dc59 <Variable is not NSData>

If I pass in an NSString, it does the same and says variable is not NSString.

Also, I can hard code key to be "A" and try to access it again as "A" with the same results.

Any ideas?

like image 240
Ryan Quick Avatar asked Oct 26 '12 15:10

Ryan Quick


1 Answers

-valueForKey: is a KVC method; use -objectForKey:

like image 60
tc. Avatar answered Sep 22 '22 07:09

tc.