简体   繁体   English

将 NSDictionary 保存到 plist

[英]Save NSDictionary to plist

I am using the code found in this post: Mulitple Arrays From Plist , with the same plist formatting.我正在使用这篇文章中的代码: Mulitple Arrays From Plist ,具有相同的 plist 格式。

This works successfully, however I do not know how to save the created arrays back into a plist, in the same format.这可以成功,但是我不知道如何以相同的格式将创建的 arrays 保存回 plist。

How would I achieve this?我将如何实现这一目标?

EDIT: It is not so much the saving that I need, but the forming of the data to save.编辑:这不是我需要的保存,而是要保存的数据的形成。
The plist is an array of dictionaries with strings and their corresponding keys. plist 是一个包含字符串及其对应键的字典数组。 All the strings with a certain key are put into an array of their own.所有具有特定键的字符串都放入自己的数组中。

How would I put that array back into the correct positions in the array of dictionaries, ready to save?我如何将该数组放回字典数组中的正确位置,准备保存?

Here's the simplest way:这是最简单的方法:

NSDictionary* dict = ...;
[dict writeToFile:@"..." atomically:YES];

See the documentation for -writeToFile:atomically: .请参阅-writeToFile:atomically:的文档。

Don't forget to create myPlistFile.plist and add it in your application resource folder.不要忘记创建myPlistFile.plist并将其添加到您的应用程序资源文件夹中。

NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

you could scan paths here and search myPlistFile.plist using for loop.您可以在此处扫描路径并使用 for 循环搜索myPlistFile.plist

NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"myPlistFile.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath: plistPath])
{
          NSString *bundle = [[NSBundle mainBundle] pathForResource:@"myPlistFile" ofType:@"plist"];
          [[NSFileManager defaultManager] copyItemAtPath:bundle toPath:plistPath error:&error];
}
[myDict writeToFile:plistPath atomically: YES];

And conversely, to load a NSDictionary FROM a file:相反,要从文件加载 NSDictionary:

+ (id)dictionaryWithContentsOfFile:(NSString *)path;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM