我按了一个清除缓存的按钮:
[[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成为ZERO?
ps:在AppDelegate.m中didFinishLaunchingWithOptions:
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:2 * 1024 * 1024
diskCapacity:20 * 1024 * 1024
diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
答案 0 :(得分:3)
我用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
这是全新安装的应用程序,没有任何网络请求,并且已经占用了一些空间,您可以在日志中看到。所以我认为它在缓存中有一些额外的开销,而且它与真实的网络数据无关。
答案 1 :(得分:0)
部分缓存是sqlLite数据库。清除缓存可以清除数据库中的记录,但不能调低数据库的大小。这就是磁盘空间似乎不受影响的原因。
答案 2 :(得分:0)
在笔测试(安全测试)期间,我遇到了iOS在cache.db中缓存URL请求/响应的问题。
我尝试使用
URLCache.shared.removeCachedResponse(用于: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)