9

When saving small amounts of data from within my App is it better to use NSUserDefaults or NSCoding? Right now I use NSCoding (encodeWithCoder/initWithCoder, etc.) but it appears that NSUserDefaults might be simpler. My total data is about a variety of Ints/Strings/MutableArray, only about a few dozen total.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
wayneh
  • 4,393
  • 9
  • 35
  • 70
  • 1
    You're comparing apples with oranges. You might use NSCoding to save something into NSUserDefaults, so what contrast are you trying to draw? – matt Apr 11 '14 at 17:21
  • It sounds like what you want is `NSPropertyListSerialization`. – iluvcapra Apr 11 '14 at 17:26
  • 1
    To further was matt stated, NSCoding is not a storage mechanism at all. What are you doing with your encoded data? That is what you should compare against using NSUserDefaults. – rmaddy Apr 11 '14 at 17:27

2 Answers2

8

I assume that by NSCoding you mean "saving objects to files after serializing them with NSCoding APIs". Although both approaches are valid for primitive data types, the NSUserDefaults approach gets more difficult once you start serializing objects with complex structures.

In contrast, saving data of NSCoding classes to files offers high degree of flexibility in terms of object structure. If you know that you are not going to need this flexibility in the future, go with NSUserDefaults; if you are not sure, stay with the files.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Yes, your assumption is correct (my question should have been stated clearer). I'll stick with the NSCoding/file method since it's already working. Thanks. – wayneh Apr 11 '14 at 17:32
0

It is my preference to use a plist file that is programmatically created

NSString *appFile;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    appFile = [documentsDirectory stringByAppendingPathComponent:@"myFile"];
    //this creates the file path


    NSDictionary* tempDict = [[NSDictionary alloc]initWithContentsOfFile:appFile];
    //this gets the data from storage

    [tempDict writeToFile:appFile atomically:YES];
    //this updates the data to storage
V-FEXrt
  • 11
  • 3