Should I use NSUserDefaults or a plist to store data?

后端 未结 9 1448
北海茫月
北海茫月 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 19:51

    Using a plist is a good choice for storing your strings if the strings are not just user settings that can go in NSUserDefaults. As was mentioned, when using a plist you must store your plist in the Documents directory in order to write to it, because you can't write into your own app's resources. When I first learned this, I wasn't clear on where your own app's Bundle directory was vs. where the Documents directory was, so I thought I'd post example code here that first copies a plist called "Strings.plist" (that you already have in your own app's Bundle directory) to the Documents directory, and then writes to it and reads from it.

    // Make a path to the plist in the Documents directory
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *stringsPlistPathIndDoc = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Strings.plist"];
    
    // Make a path to the plist in your app's Bundle directory
    NSString *stringsPlistPathInBundle = [[NSBundle mainBundle] pathForResource:@"Strings" ofType:@".plist"];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    // Check first that you haven't already copied this plist to the Documents directory
    if (![fileManager fileExistsAtPath:stringsPlistPathIndDoc])
    {
        NSError *error;
    
        // Copy the plist from the Bundle directory to the Documents directory 
        [fileManager copyItemAtPath:stringsPlistPathInBundle toPath:stringsPlistPathIndDoc error:&error];
    }
    
    // Write your array out to the plist in the Documents directory
    NSMutableArray *stringsArray = [[NSMutableArray alloc] initWithObjects:@"string1", @"string2", @"string3", nil]; 
    [stringsArray writeToFile:stringsPlistPathIndDoc atomically:YES];
    
    // Later if you want to read it:
    stringsArray = [[NSMutableArray alloc] initWithContentsOfFile:stringsPlistPathIndDoc];
    

提交回复
热议问题