removeAllCachedResponses 无法清除 sharedURLCache?
Posted
技术标签:
【中文标题】removeAllCachedResponses 无法清除 sharedURLCache?【英文标题】:removeAllCachedResponses can not clear sharedURLCache? 【发布时间】:2015-08-04 07:57:49 【问题描述】:我做了一个按钮来清除我的缓存:
[[NSURLCache sharedURLCache]removeAllCachedResponses];
完成后,我检查 sharedURLCache 的大小:
NSInteger sizeInteger = [[NSURLCache sharedURLCache] currentDiskUsage];
float sizeInMB = sizeInteger / (1024.0f * 1024.0f);
sizeInMB 为 0.17,有时为 0.13。从不 0.0。为什么 removeAllCachedResponses 没有使 sharedURLCache 为零?
ps:在 AppDelegate.m 中 didFinishLaunchingWithOptions:
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:2 * 1024 * 1024
diskCapacity:20 * 1024 * 1024
diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
【问题讨论】:
【参考方案1】:我用 NSURLCache 做了一个小实验。代码和日志如下:
NSUInteger memorySize = 1024 * 1024 * 64;
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:memorySize diskCapacity:memorySize diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
NSLog(@"cap: %ld", [[NSURLCache sharedURLCache] diskCapacity]);
NSInteger sizeInteger = [[NSURLCache sharedURLCache] currentDiskUsage];
float sizeInMB = sizeInteger / (1024.0f * 1024.0f);
NSLog(@"size: %ld, %f", (long)sizeInteger, sizeInMB);
[[NSURLCache sharedURLCache] removeAllCachedResponses];
sizeInteger = [[NSURLCache sharedURLCache] currentDiskUsage];
sizeInMB = sizeInteger / (1024.0f * 1024.0f);
NSLog(@"size: %ld, %f", (long)sizeInteger, sizeInMB);
[[NSURLCache sharedURLCache] removeAllCachedResponses];
sizeInteger = [[NSURLCache sharedURLCache] currentDiskUsage];
sizeInMB = sizeInteger / (1024.0f * 1024.0f);
NSLog(@"size: %ld, %f", (long)sizeInteger, sizeInMB);
日志:
2015-08-05 11:26:29.901 lagoon[26845:533709] cap: 67108864
2015-08-05 11:26:29.904 lagoon[26845:533709] size: 86016, 0.082031
2015-08-05 11:26:29.907 lagoon[26845:533709] size: 123128, 0.117424
2015-08-05 11:26:29.910 lagoon[26845:533709] size: 123128, 0.117424
这是全新的应用程序安装,没有任何网络请求,并且已经占用了一些空间,您可以在日志中看到。所以我认为它在缓存中有一些额外的开销,它与真实的网络数据无关。
【讨论】:
谢谢。我也参加了考试。在设备和模拟器上,大小都是 0.117424。我想我必须减去这些才能向用户展示。【参考方案2】:在笔测试(安全测试)期间,我遇到了 ios 在 cache.db 中缓存 url 请求/响应的问题。
我尝试过使用
URLCache.shared.removeCachedResponse(for: URLRequest) 和 URLCache.shared.removeAllCachedResponses()
从 API 调用获得响应后,上述两个 API 似乎都不起作用
然后通过在 AppDelegate 中的 didFinishLaunchingWithOptions 中添加以下两行代码来使其工作
// first remove all url cache from previous versions of app
URLCache.shared.removeAllCachedResponses()
// As we do not want to cache any request response so
// updated shared instance of url cache with custom url cache where
// memoryCapacity = 0, diskCapacity = 0 and diskPath = nil
URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)
【讨论】:
【参考方案3】:部分缓存是 sqlLite 数据库。清除缓存可以清除数据库中的记录,但不会缩小数据库的大小。这就是磁盘空间似乎不受影响的原因。
【讨论】:
以上是关于removeAllCachedResponses 无法清除 sharedURLCache?的主要内容,如果未能解决你的问题,请参考以下文章