iOS上的NSURLConnection不会尝试缓存大于50KB的对象 [英] NSURLConnection on iOS doesn't try to cache objects larger than 50KB
问题描述
尽管有Apple的文档另外说明,iOS上的 NSURLCache
根本不进行任何磁盘(闪存)缓存。您可以继承 NSURLCache
以更改获取和存储操作的行为以使用该磁盘(如 SDURLCache
确实如此),但由于以下严格的缓存使用和实施限制,这不起作用如你所料:
Despite Apple's documentation indicating otherwise, NSURLCache
on iOS doesn't do any disk (flash) caching at all. You can subclass NSURLCache
to change the behaviour of the fetch and store operations to use the disk (like SDURLCache
does), but due to the following severe limitations of how the cache is used and implemented, this doesn't work as well as you'd expect:
-
NSURLConnection
甚至不会调用storeCachedResponse:forRequest:
用于超过50KB的文件(确切地说> = 52428字节)。这使得子类化NSURLCache
对我们的使用毫无意义(200KB图像),因为它甚至不会进入缓存。因此,我们必须在NSURLConnection
以上的级别手动添加缓存。 - 即使一个人调用NSURLCache的内置
storeCachedResponse:forRequest:
手动,如果响应小于约180KB,它只将响应存储在内存中。我通过手动调用storeCachedResponse测试了这一点,并发现前面/后面的currentMemoryUsage
对于大约180KB以上的数据长度没有变化。所以我们也必须编写自己的LRU内存缓存。
NSURLConnection
doesn't even callstoreCachedResponse:forRequest:
for files over about 50KB (>= 52428 bytes, to be exact). This makes subclassingNSURLCache
pointless for our use (200KB images), because it won't even get to the cache. As a result, we have to add caching manually at a level aboveNSURLConnection
.- Even when one calls the NSURLCache's built-in
storeCachedResponse:forRequest:
manually, it only stores the response in memory if it's less than about 180KB. I tested this by calling storeCachedResponse manually and seeing that the before/aftercurrentMemoryUsage
didn't change for data lengths above about 180KB. So we have to write our own LRU memory caching too.
还有其他人注意到这些问题吗?或者有什么我缺少的东西?
Has anyone else noticed these issues? Or is there something I'm missing?
仅供参考,我在模拟器和iPad 2上运行iOS 4.3。
FYI, I'm running iOS 4.3 in the simulator and on an iPad 2.
推荐答案
我建议使用ASIHTTPRequest库而不是NSURLRequest:
I'd suggest using ASIHTTPRequest library instead of NSURLRequest:
http://allseeing-i.com/ASIHTTPRequest/How-to-use
它有一个强大的缓存API:
It has a robust caching API:
http://allseeing-i.com/ASIHTTPRequest/How-to-use#using_a_download_cache
这篇关于iOS上的NSURLConnection不会尝试缓存大于50KB的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!