在iOS设备中,如何在内存警告时清除URL缓存?

3

在收到内存警告时清除共享的NSURLCache是否是一个好的做法?就像这样:

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

我可以假设这样做是否也会不必要地清除磁盘缓存?

如果是这样的话,是否可以只清除内存缓存?


我不这么认为,你应该清除图像缓存。 - Rajan Balana
@RajanBalana 你知道怎么清除图片缓存吗? - zt9788
@zt9788,你找到清除图像缓存的方法了吗? - Nikita P
@NikitaP 我一点也不知道。 - zt9788
1个回答

5

当出现内存警告时,您只需要清除内存缓存而不是磁盘缓存。使用removeAllCachedResponses的问题在于它会清除两者。根据我的测试,这似乎只清除了内存缓存。

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

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

我的唯一担忧是线程问题。这篇文章底部有一个脚注,点击这里查看。
在StackOverflow上有许多关于通过重新创建NSURLCache来清除缓存的建议,但是我们发现当请求在重建缓存时发生在另一个线程时,这会导致偶尔的崩溃。因此,我们的建议是在应用程序启动时创建缓存,并在适当时清除它。
上述解决方案不重新创建缓存,但可能仍然存在相同的问题,我没有进行过详尽的测试。

有趣。谢谢@Robert! - hpique
URLCache.shared.currentMemoryUsage before and after your code gives the same value, so setting memoryCapacity to 0 seems doesn't work. On the other hand, after URLCache.shared.removeAllCachedResponses(), currentMemoryUsage is set to 0 - rafalkitta

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接