NSCache: When accessing a cached item, it is always required to "not encode with key values"

I am trying to use NSCache to store PNG as NSData. Whenever I try to pull one from the cache, the cache is empty or not, I get:

2012-10-26 09: 49: 28.860 SledMap [55917: 11503] * The application terminated due to the unselected exception "NSUnknownKeyException", reason: "[valueForUndefinedKey:]: this class is not a key value compatible with the encoding for key 0_0_5 ' .

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

I declare my cache:

@property (nonatomic, strong) NSCache *tileCache; 

Select 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, 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 zero, which happens when I do self.tileCache NSMutableDictionary instead of NSCache. In addition, the debugging area says:

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

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

In addition, I can hard code the key as β€œA” and try to access it again as β€œA” with the same results.

Any ideas?

+7
source share
2 answers

-valueForKey: - KVC method; use -objectForKey:

+17
source

I don’t think the problem is NSData, I think it could be with your key. Take a close look at this stringWithFormat - you should probably use% d instead of% i if they are both integers because% d matches 32-bit. If they are floating, you should use% f.

-one
source

All Articles