0

我扩展了 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)。有什么建议吗?

4

1 回答 1

1

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

你应该做

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

或者

image = [UIImage imageWithData:[_caches objectForKey:[NSURL URLWithString:keyString]]];
于 2015-05-13T11:33:45.557 回答