vs own Plist

2019-06-02 09:42发布

问题:

In my past projects I always made a NSObject-HelperClass which interacts with a selfmade-Plist. Now i hear I can use [NSUserDefaults standardUserDefaults] and have also my dictionary.

So why should I use UserDefaults instead of my own NSObject which massages the plist?

cheers endo

回答1:

NSUserDefaults is a convenient way to store some preferences and the current state of the application (ex: "remember me" checkbox set to yes or no). You should only use it for this kind of data.

You can also use a custom PList to store this kind of information but it can be overkill.

The key question is how large are the data you need to store ?

small dataset => NSUserDefaults

large dataset => PList

You should also consider using CoreData if you have serious storage needs.



回答2:

If I recall correctly, Apple is recommended to use NSUserDefaults primarily for user defaults. Maybe I heard it in one of the videos from WWDC 2010.

The biggest problem with NSUserDefaults is that they are 'semi-immutable'. You'll have to replace whole collection with setObjectForKey even if you change only one object contained in that collection.

Other than that, I think it is fine to use NSUserDefaults if you're ok with it.



回答3:

NSUserDefaults has a number of properties that could be useful; for example it will automatically coalesce changes to avoid writing to disk too often. Also you can manipulate it using the 'defaults' command in Terminal which can be handy for testing. Lastly, it's threadsafe which is tricky to do properly.