37
votes

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html says it is

...should prevent users from editing that preference by disabling any appropriate controls.

The NSUserDefaults class is thread-safe. Persistence of NSURL and file reference URLs...

This long discussion says it isn't

http://www.cocoabuilder.com/archive/cocoa/155227-nsuserdefaults-thread-safety.html

So which one is right? Also why the difference of opinion.

2
Keep in mind that the discussion you posted a link to is from 2006, so it's entirely possible that NSUserDefaults has become thread safe since then. - UIAdam
Anyone knows more about history? Perhaps NSUserDefaults is thread safe but it's singleton is not. That kind of thing. - user4951
Unless you have recent evidence to suggest otherwise, I'd guess the docs are probably correct in saying that the class is thread safe. Whether it's a custom instance or the standardUserDefaults instance (I assume that's what you mean by "singleton"), they are all ultimately instances of the same class and will either be thread safe or not. - UIAdam
NSUserDefaults has gone through many implementations over the years. The thread-safety guarantees have been getting steadily better with each one, it's in quite good shape in recent OS releases. - Catfish_Man

2 Answers

73
votes

The Apple iOS 5.1 and OS X 10.7 documentation say that it is thread-safe; therefore it is thread-safe.

47
votes

Speaking for 10.10 and iOS8 if you looking into the implementation you'll find that -[NSUserDefaults setObject:forKey:] is calling __CFPreferencesSetAppValueWithContainer, which will eventually end up in +[CFPrefsSource withSourceForIdentifier:user:byHost:container:perform:]. This method is using a pthread_mutex_t to lock the access to the dictionary containing the values.

So NSUserDefaults is thread safe.