سؤال

Is it a good practice to clear the shared NSURLCache when receiving a memory warning? Something like this:

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
}

Am I correct to assume that this would also unnecessarily clear the disk cache?

If so, it is possible to only clear the memory cache?

هل كانت مفيدة؟

المحلول

When there is a memory warning you only need to clear the in memory cache not the on disk cache. The issue with removeAllCachedResponses is that it will clear both. From my tests this seems to clear just the in memory cache.

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {

    NSURLCache * const urlCache = [NSURLCache sharedURLCache];
    const NSUInteger memoryCapacity = urlCache.memoryCapacity;
    urlCache.memoryCapacity = 0;
    urlCache.memoryCapacity = memoryCapacity;
}

My only concern is with threading issues. There is a foot note at the bottom of this article.

There are a lot of recommendations on StackOverflow about purging the NSURLCache by recreating it, however, we’ve seen this lead to occasional crashes when requests occur on another thread while the cache is being recreated. Our advice is therefore to create the cache once when the app starts and purge it when appropriate.

The above solution does not re-create the cache, however it might still suffer from the same issue, I haven't tested this extensively.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top