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.
Thread SafetyThe UserDefaults class is thread-safe.
Types stored in NSUserDefaultsplist type can be stored by NSUserDefaults . These types are NSString(String) , NSArray(Array) , NSDictionary(Dictionary) (for both NSArray and NSDictionary types their contents must be property list objects), NSNumber(Int, Float, Double, Boolean) , NSDate and NSData .
All the contents saved by NSUserDefaults is saved inside a plist file that can be found under Library -> Preferences -> $AppBundleId.
Currently, there is only a size limit for data stored to local user defaults on tvOS, which posts a warning notification when user defaults storage reaches 512kB in size, and terminates apps when user defaults storage reaches 1MB in size.
The Apple iOS 5.1 and OS X 10.7 documentation say that it is thread-safe; therefore it is thread-safe.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With