Memory leak when using SDURLCache (subclass of NSURLCache)

I am using Olivier Poitrey SDURLCache (github link) as an alternative NSURLCacheto enable disk caching in an iPhone application.

It works very well, but there is a curious leak NSHTTPURLResponseInternalwhen the disk cache object is returned (there is no leak when the object is returned from memory or the object was not found). The following code snippet shows how SDURLCache reads data from disk:

- (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;
}

The stack trace for each tag NSHTTPURLResponseInternalcontains two code references SDURLCache.

The first points to a string [accesses setObject:[NSDate date] forKey:cacheKey];. The second and last indicates the following:

@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 Olivier Poitrey,

NSURLCache ,

+3
1

, . NSURLCache iOS 5.0 , RAM . , SDURLCache 5.0 , SDURLCache.

+1

Source: https://habr.com/ru/post/1748914/


All Articles