问题描述
我将存储一些字符串(可能是 10-20 个).我不确定是否应该使用 NSUserDefaults 来保存它们,或者将它们写到 plist 中.什么被认为是最佳实践?NSUserDefaults 看起来代码行更少,因此实现起来更快.
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? NSUserDefaults seems like it is less lines of code, therefore quicker to implement.
我想补充一点,这些字符串值将由用户添加/删除.
I'd like to add that these string values will be added/removed by the user.
推荐答案
我假设是一个数组,但它也适用于字典.
I am assuming an array, but it will work with dictionaries too.
Userdefaults、Core Data 和 Plists 都可以读/写,但如果你使用 plist,你需要注意你把它放在什么目录中.请参阅下面的 plist 部分.
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];
从用户默认值中读取:
NSArray *stringsArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"MyStrings"];
Plist:
如果您的字符串将被修改,您将需要编写和读取 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.
要有一个读/写plist,首先要找到文档目录
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"];
创建数组(我假设字符串是 string1,...)
Create the array (I am assuming the strings are string1, ...)
NSArray *stringsArray = [[NSArray alloc] arrayWithObjects: string1, string2, string3, nil];
写入文件
Write it to file
[stringsArray writeToFile:stringsPlistPath atomically:YES];
阅读plist:
找到文档目录
Find the documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *stringsPlistPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Strings.plist"];
阅读:
Read it in:
NSArray *stringsArray = [NSArray arrayWithContentsOfFile:stringsPlistPath];
这篇关于我应该使用 NSUserDefaults 还是 plist 来存储数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!