【问题标题】:Memory Leak when using SDURLCache (subclass of NSURLCache)使用 SDURLCache(NSURLCache 的子类)时的内存泄漏
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-17
      • 2015-09-14
      • 2011-04-07
      • 2015-03-29
      • 2011-10-15
      • 2018-12-26
      • 2011-05-26
      • 2012-08-26
      相关资源
      最近更新 更多