我正在使用Olivier Poitrey's SDURLCache(github link)作为NSURLCache的替代,以在iphone应用程序中启用磁盘缓存。
它工作得很好,但当磁盘缓存对象返回时(当对象从内存中返回或没有找到对象时没有泄漏),很奇怪地泄漏了一个cc。以下代码段显示了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泄漏的堆栈跟踪都包含对NSHTTPURLResponseInternal代码的两个引用。
第一个指向线SDURLCache。第二点,也是最新的一点是:
@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固有值并处理内存缓存,它可以修复漏洞。

最佳答案

不是答案本身,而是意识。iOS5.0及更高版本上的nsurlcache现在默认缓存到flash和ram。因此,如果使用sdurlcache是为了获得磁盘上缓存,并且目标是5.0及更高版本,那么就没有理由使用sdurlcache。

关于iphone - 使用SDURLCache(NSURLCache的子类)时的内存泄漏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2992704/

10-12 05:32