是否可以仅清除NSURLCache中的内存缓存?

时间:2014-05-09 13:22:55

标签: ios cocoa-touch

This post建议这样做:

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

但是,这将同时采用磁盘和内存缓存。这样的事情是否只能驱逐内存缓存?

NSURLCache *cache = [NSURLCache sharedURLCache];
NSUInteger currentMemoryCapacity = cache.memoryCapacity;

// Not sure if this works? Docs seem to say it will trigger an evict.
// https://developer.apple.com/library/mac/documentation/cocoa/reference/foundation/Classes/NSURLCache_Class/Reference/Reference.html#//apple_ref/occ/instm/NSURLCache/setMemoryCapacity:
cache.memoryCapacity = 0; 
cache.memoryCapacity = currentMemoryCapacity;

2 个答案:

答案 0 :(得分:1)

是的,该代码应该驱逐内存缓存。 (在iOS 7.1.1中,在我的简短测试中也是如此。)

如果您正在寻找对缓存的更好控制,请查看具有(例如)-removeAllCachedResponsesInMemory方法的Peter Steinberger's fork of SDURLCache

答案 1 :(得分:0)

这似乎不再起作用(在iOS 9.2模拟器上测试)

虽然缓存报告的memoryCapacity发生了变化,但报告的实际memoryUsage却没有: - (