Is NSUserDefaults thread safe for exchanging data between extensions in IOS?

The documentation for extending the app under "Sharing Data with Your Content" uses NSUserDefaults to do this and writes a little more that

"To avoid data corruption, you must synchronize data access. Use Core Data, SQLite, or> Posix locks to help coordinate data access in a shared container.

But when I look at the documentation for NSUserDefaults,

"The NSUserDefaults class is thread safe."

So do I need to use some kind of lock when using NSUserDefaults between my extension and container or not?


source to share

2 answers

Thread safety refers to the ability to modify data structures in memory from one thread in a way that does not damage the ability of other threads to view or modify those structures as well. When you use NSUserDefaults

to exchange data between an application extension and its containing application, you are not exchanging data in memory between multiple threads, you are sharing data on disk between multiple processes, so thread safety discussions do not apply.

The documentation for NSUserDefaults


does not answer exactly, but one can almost certainly assume that it uses atomic file writing - that is, there is no danger of one process reading a file that was partially written by another process. If you are concerned about race conditions or other timing issues between when an application writes defaults and your extension reads them (or vice versa), just make sure to be synchronize

right after important writes and just before important readings.

The data corruption comment applies to normal read / write operations - naive reading or writing of a file in two processes can lead to data corruption, as one process can read a partially written file or partially overwrite the contents of a file. If you are doing your own file I / O yourself, you need some sort of coordination mechanism (e.g. NSFileCoordinator

, but be careful, that only works between iOS apps / extensions in iOS 8.2 and newer ). Or you can use higher level utilities that do their own coordination, such as CFPreferences

/ NSUserDefaults

, SQLite, master data, or Posix file locks.

TL; DR: Yes, you can safely NSUserDefaults

share between an extension and its containing application. Just follow the guidelines in Apple's App Extension Guide .



The documentation is not very clear, as it uses NSUserDefaults

one of the communication methods as a basic example, but also covers other options without much delay. You should be secure enough to use NSUserDefaults

without trying to get the lock first, I was building a Today extension using that and I had no data corruption issues. I call synchronize

after every entry, but to ensure that the data is saved immediately.



All Articles