我正在使用Olivier Poitrey 的 SDURLCacheNSURLCache
(github 链接)作为在 iPhone 应用程序中启用磁盘缓存的替代方法。
它工作得很好,但奇怪的NSHTTPURLResponseInternal
是在返回磁盘缓存对象时泄漏(从内存返回对象或找不到对象时没有泄漏)。以下代码片段显示了 SDURLCache 如何从磁盘读取数据:
- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request
{
NSCachedURLResponse *memoryResponse = [super cachedResponseForRequest:request];
if (memoryResponse)
{
return memoryResponse;
}
NSString *cacheKey = [SDURLCache cacheKeyForURL:request.URL];
// NOTE: We don't handle expiration here as even staled cache data is necessary for NSURLConnection to handle cache revalidation.
// Staled cache data is also needed for cachePolicies which force the use of the cache.
NSMutableDictionary *accesses = [self.diskCacheInfo objectForKey:kSDURLCacheInfoAccessesKey];
if ([accesses objectForKey:cacheKey]) // OPTI: Check for cache-hit in a in-memory dictionnary before to hit the FS
{
NSCachedURLResponse *diskResponse = [NSKeyedUnarchiver unarchiveObjectWithFile:[diskCachePath stringByAppendingPathComponent:cacheKey]];
if (diskResponse)
{
// OPTI: Log the entry last access time for LRU cache eviction algorithm but don't save the dictionary
// on disk now in order to save IO and time
[accesses setObject:[NSDate date] forKey:cacheKey];
diskCacheInfoDirty = YES;
// OPTI: Store the response to memory cache for potential future requests
[super storeCachedResponse:diskResponse forRequest:request];
return diskResponse;
}
}
return nil;
}
每个泄漏的堆栈跟踪都包含对代码NSHTTPURLResponseInternal
的两个引用。SDURLCache
第一条指向线[accesses setObject:[NSDate date] forKey:cacheKey];
。第二点,也是最新的点如下:
@implementation NSCachedURLResponse(NSCoder)
- (id)initWithCoder:(NSCoder *)coder
{
return [self initWithResponse:[coder decodeObjectForKey:@"response"]
data:[coder decodeDataObject]
userInfo:[coder decodeObjectForKey:@"userInfo"]
storagePolicy:[coder decodeIntForKey:@"storagePolicy"]];
}
@end
有没有人遇到过这个问题?关于解决方案的任何想法?让我知道是否应该发布更多代码示例。
干杯。
更新:来自代码作者Olivier Poitrey的推文
我正计划删除 NSURLCache 继承性并处理内存缓存,它可能会修复泄漏