我扩展了NSCache并创建了一个Singleton类,如下所示

+(instancetype)sharedDataCache {
if (!sharedDataCache) {
    sharedDataCache = [[QDataCache alloc] init];
    [sharedDataCache setTotalCostLimit:19999];
    [sharedDataCache setCountLimit:15];
    [[NSNotificationCenter defaultCenter] addObserver:sharedDataCache selector:@selector(removeAllObjects) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
}
return sharedDataCache;
}


在一类中设置对象:

[_cache setObject:receivedData forKey:[[connection currentRequest]URL]];



在其他类中获取对象:

image = [UIImage imageWithData:[_caches objectForKey:keyString]];//keystring is the url


这两个键在日志中都是相同的,但是我得到的是NULL :(。。'如果我用相同的字符串对键进行硬编码就可以了。'但是我想要唯一的键(URL)。有什么建议吗?

最佳答案

您不能只通过NSURL键来放置值,然后通过NSString键来获取值。 NSURL对象和NSString对象的哈希值不相同。

你应该做

[_cache setObject:receivedData forKey:[[[connection currentRequest]URL] absoluteString]];


要么

image = [UIImage imageWithData:[_caches objectForKey:[NSURL URLWithString:keyString]]];

关于ios - 将URL设置为NSCache的键不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30181895/

10-14 20:03