Should I use NSUserDefaults or a plist to store data?

后端 未结 9 1385
北海茫月
北海茫月 2020-11-28 19:17

I will be storing a few strings (maybe 10-20). I am not sure if I should use NSUserDefaults to save them, or write them out to a plist. What is considered best practice? NSU

相关标签:
9条回答
  • 2020-11-28 20:09

    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];
    
    0 讨论(0)
  • 2020-11-28 20:10

    Using .plist

    1. Create a plist using Xcode

    Write a value to plist

    NSURL *plistURL = [[NSBundle mainBundle] URLForResource:@"settings" withExtension:@"plist"];
    
     NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfURL:plistURL];
     [dict setValue:@"value" forKey:@"key"];
     [dict writeToURL:plistURL atomically:YES];
    

    Read a value from plist

    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfURL:plistURL];
    NSString *myValue = [dict valueForKey:@"key"];
    
    0 讨论(0)
  • 2020-11-28 20:16

    The recommended way to persist data like this is to use Core Data. While NSUserDefaults can be used to store more or less anything it's only supposed to be used to store preferences.

    0 讨论(0)
提交回复
热议问题