【发布时间】:2011-02-28 21:06:38
【问题描述】:
我正在使用 Olivier Poitrey's SDURLCache(github 链接)作为 NSURLCache 的替代品,以在 iPhone 应用程序中启用磁盘缓存。
它工作得很好,但奇怪的是在返回磁盘缓存对象时泄漏NSHTTPURLResponseInternal(从内存返回对象或找不到对象时没有泄漏)。以下代码 sn -p 展示了 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
以前有人遇到过这个问题吗?关于解决方案的任何想法?如果我应该发布更多代码示例,请告诉我。
干杯。
更新:Tweet from Olivier Poitrey,代码作者
我正在计划移除 NSURLCache 继承性并处理内存缓存,它可能会修复泄漏
【问题讨论】:
标签: iphone objective-c cocoa-touch memory-leaks nsurlcache