Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is NSUserDefault thread safe?

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.

like image 838
user4951 Avatar asked Jun 02 '12 17:06

user4951


People also ask

Is UserDefaults thread safe?

Thread SafetyThe UserDefaults class is thread-safe.

What types can you store natively in NSUserDefaults?

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 .

Where are NSUserDefaults stored?

All the contents saved by NSUserDefaults is saved inside a plist file that can be found under Library -> Preferences -> $AppBundleId.

How much data can User defaults hold?

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.


2 Answers

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

like image 163
GoZoner Avatar answered Sep 22 '22 21:09

GoZoner


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.

like image 33
McZonk Avatar answered Sep 23 '22 21:09

McZonk