简体   繁体   English

在iOS中清除内存警告上的url缓存

[英]Clearing the url cache on memory warning in iOS

Is it a good practice to clear the shared NSURLCache when receiving a memory warning? 在收到内存警告时清除共享的NSURLCache是一个好习惯吗? 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. removeAllCachedResponses的问题是它将清除它们。 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. 关于通过重新创建NSURLCache来清除NSURLCache有很多关于StackOverflow的建议,但是,我们已经看到这会导致在重新创建缓存时在另一个线程上发生请求时偶尔会发生崩溃。 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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM