Question

I know NSCache is thread safe, however I can't find out any document mentioned that NSURLCache is thread safe.

Was it helpful?

Solution 3

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!

OTHER TIPS

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 :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top