Should I use NSUserDefaults or a plist to store data? Should I use NSUserDefaults or a plist to store data? objective-c objective-c

Should I use NSUserDefaults or a plist to store data?


I am assuming an array, but it will work with dictionaries too.

Userdefaults, Core Data and Plists can all be read/write but if you use a plist you need to pay attention in what dir you put it. See the plist part down below.

Core Data I think it's way too much overkill, it's just strings.It's supposed to be used when you want to persist more complex objects.

NSUserDefaults:

It's pretty fast and easy to do, though it's supposed to store only user settings.To write them to the userdefaults:

NSArray *stringsArray = [[NSArray alloc] arrayWithObjects: string1, string2, string3, nil];[[NSUserDefaults standardUserDefaults] setObject:stringsArray forKey:@"MyStrings"];[[NSUserDefaults standardUserDefaults] synchronize];

To read the from the userdefaults:

NSArray *stringsArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"MyStrings"];

Plist:

If your strings are going to be modified you will need to write and read a plist but you cant't write into your app's resources.

  1. To have a read/write plist first find the documents directory

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *stringsPlistPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Strings.plist"];
  2. Create the array (I am assuming the strings are string1, ...)

    NSArray *stringsArray = [[NSArray alloc] arrayWithObjects: string1, string2, string3, nil];
  3. Write it to file

    [stringsArray writeToFile:stringsPlistPath atomically:YES];

To read the plist:

  1. Find the documents directory

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *stringsPlistPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Strings.plist"];
  2. Read it in:

    NSArray *stringsArray = [NSArray arrayWithContentsOfFile:stringsPlistPath];


If you are storing 10-20 strings and are looking for not too many lines of code, core data is certainly much too much overhead. I recommend going with the plist. Not a lot of code:

NSURL *plistURL = [[NSBundle mainBundle] URLForResource:@"MyStrings" withExtension:@"plist"];NSArray *stringArray = [NSArray arrayWithContentsOfURL:plistURL];


iOS ultimately stores all NSUserDefaults data to a plist file. So it will not affect the performance if that is your concern. I personally prefer using NSUserDefaults for small data and plist for a relatively large set of data.

Note: Never store any sensitive information in NSUserDefaults as anyone can see that data.