10

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?

Ryan Quick
  • 123
  • 4

2 Answers2

25

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

tc.
  • 33,468
  • 5
  • 78
  • 96
-1

I don't think that the issue is the NSData, I think it might be with your key. Take a close look at that stringWithFormat - you should probably be using %d instead of %i if they are both integers, because %d is 32bit compliant. If they are floats you should be using %f.

Scott Allen
  • 1,199
  • 1
  • 12
  • 14
  • If I hard-code the key to be just "A" or anything else, I get the same results, and using `key` as above works when it's an NSMutableDictionary instead of NSCache. – Ryan Quick Oct 26 '12 at 15:23