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];
    

Leave a Comment