NSUserDefaults vs NSCoding
Asked Answered
O

2

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.

Othello answered 11/4, 2014 at 17:19 Comment(3)
You're comparing apples with oranges. You might use NSCoding to save something into NSUserDefaults, so what contrast are you trying to draw?Brainwash
It sounds like what you want is NSPropertyListSerialization.Rubierubiginous
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.Angi
H
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.

Hallucination answered 11/4, 2014 at 17:26 Comment(1)
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.Othello
B
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
Barnard answered 11/4, 2014 at 17:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.