我正在尝试使用 NSCache 将 PNG 存储为 NSData。每当我尝试从缓存中取回一个时,无论缓存是否为空,我都会得到:
2012-10-26 09:49:28.860 SledMap[55917:11503] * 由于未捕获的异常“NSUnknownKeyException”而终止应用程序,原因:“[valueForUndefinedKey:]:此类不是 key 键 0_0_5 的值编码兼容。'
如果我保留代码原样,但将 NSCache 更改为 NSMutableDictionary,它可以正常工作。
我声明我的缓存:
@property (nonatomic, strong) NSCache *tileCache;
分配它(在 viewDidLoad 中):
self.tileCache = [[NSCache alloc] init];
self.tileCache.delegate = self;
向缓存中添加内容:
NSString *key = [NSString stringWithFormat:@"%i_%i_%i",x,y,endLevel];
NSData *pngData = [NSData dataWithData:UIImagePNGRepresentation(image)];
[self.tileCache setObject:pngData forKey:key];
然后当我将其取回时,出现上述错误。
NSString *key = [NSString stringWithFormat:@"%i_%i_%i",x,y,endLevel];
NSData *tile = [self.tileCache valueForKey:key]; //This is the line it crashes on
如果它是空的,我希望它只返回 nil,这就是我将 self.tileCache 设为 NSMutableDictionary 而不是 NSCache 时发生的情况。此外,在调试区域,它说:
tile = NSData * 0x0134dc59 <Variable is not NSData>
如果我传入一个 NSString,它会做同样的事情并说变量不是 NSString。
此外,我可以将 key
硬编码为“A”,然后尝试以“A”身份再次访问它,结果相同。
有什么想法吗?
最佳答案
-valueForKey:
是一个KVC方法;使用 -objectForKey:
关于objective-c - NSCache:尝试访问缓存项时总是得到 "not key value coding-compliant",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13089452/