简体   繁体   中英

Is NSURLCache thread safe?

我知道NSCache是线程安全的,但是我找不到任何提到NSURLCache线程安全的文档。

Unless the documentation explicitly says that NSURLCache is thread safe, then it is not thread safe.

(The docs say nothing about threads. Therefore, not thread safe.)

And always check the docs again every now and then. The thread safety rules have changed since I wrote this answer.

Allow me to merge the two brilliant answers into a third one, now with a reference to the updated documentation :

Thread Safety

In iOS 8 and later, and macOS 10.10 and later, NSURLCache is thread safe.

Although NSURLCache instance methods can safely be called from multiple execution contexts at the same time, be aware that methods like cachedResponseForRequest: and storeCachedResponse:forRequest: have an unavoidable race condition when attempting to read or write responses for the same request.

Subclasses of NSURLCache must implement overridden methods in such a thread safe manner.

That is, unless you explicitly call cachedResponseForRequest: , storeCachedResponse:forRequest: or other "methods alike", you'll be safe across threads. What "methods like" these are, seems to be an exercise left for the reader, but since you would hit an "unavoidable race condition" there is a good chance you will figure out eventually :-)

Normally I'd take @bbum's stance on this, but in the case of NSURLCache disagree.

NSURLConnection is thread safe, in the sense that a given instance can be scheduled on a thread of your choosing (but don't try to schedule a single instance on multiple threads!)

By default, connections all interact with +[NSURLCache sharedCache] . Logically, this means either NSURLCache is itself thread safe, or offers a locking mechanism which clients can explicitly call themselves. Since the latter doesn't exist, I deduce NSURLCache is thread safe.

Would still like this to be documented officially, mind!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM