Thread safety refers to the ability to change in-memory data structures from one thread in a way that doesn't damage the ability of other threads to also view or change those structures. When you use NSUserDefaults
to share data between an app extension and its containing app, you're not sharing in-memory data between multiple threads, you're sharing on-disk data between multiple processes, so discussions of thread safety do not apply.
The documentation for NSUserDefaults
synchronize
doesn't say for sure, but one can almost certainly assume that it uses an atomic file write — that is, there's no danger of one process reading a file that's been partially written by another process. If you're concerned about race conditions or other timing issues between when your app writes defaults and your extension reads them (or vice versa), just be sure to synchronize
immediately after important writes and immediately before important reads.
The comment about data corruption applies to plain file read/write operations — naively reading or writing a file in two processes can result in data corruption, because one process might read a partially written file or partially overwrite file contents. If you're doing your own file I/O directly, you need some sort of coordination mechanism (like NSFileCoordinator
, but beware that only works correctly between iOS apps/extensions in iOS 8.2 and newer). Or you can use higher level utilities that do their own coordination, like CFPreferences
/NSUserDefaults
, SQLite, Core Data, or Posix file locks.
TLDR: Yes, you can safely use NSUserDefaults
to share between an extension and its containing app. Just follow the recommendations in Apple's app extensions guide.