使用SDURLCache时的内存泄漏(NSURLCache的子类)

时间:2010-06-07 20:00:38

标签: iphone objective-c cocoa-touch memory-leaks nsurlcache

我正在使用Olivier Poitrey's SDURLCache(github链接)作为NSURLCache的替代方案,以便在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 

以前有人遇到过这个问题吗?有关解决方案的任何想法?如果我发布更多代码示例,请告诉我。

干杯。

更新:Tweet from Olivier Poitrey,代码的作者

  

我打算删除NSURLCache inherency并处理内存缓存,它可能会修复漏洞

1 个答案:

答案 0 :(得分:1)

本身不是答案,而是意识。 iOS 5.0及更高版本的NSURLCache现在默认缓存到闪存和RAM。因此,如果您使用SDURLCache来获取磁盘缓存,并且目标是5.0及更高版本,则没有理由使用SDURLCache。