我按了一个按钮来清除我的缓存:
[[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];
我用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
它是全新安装的应用程序,没有任何网络请求,并且已经占用了一些空间,您可以在日志中看到。所以我认为它在缓存中有一些额外的开销,而且它与真实的网络数据无关。
部分缓存是一个sqlite数据库。清除缓存可以清除数据库中的记录,但不能调低数据库的大小。这就是磁盘空间似乎不受影响的原因。
在笔测试(安全测试)期间,我在cache.db中遇到了iOS缓存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)