xcode 如何写入 plist 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4116179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 19:54:04  来源:igfitidea点击:

How can I write to a plist file?

iphoneobjective-cxcode

提问by Andrew

I wrote this small bit of code to write to a plist file. I am not getting any errors or warnings from XCode, so I am really lost. "Root" is not defined in this code section, but it is just a dictionary of the data that I pulled from the plist.

我写了一小段代码来写入 plist 文件。我没有从 XCode 收到任何错误或警告,所以我真的很迷茫。此代码部分中未定义“Root”,但它只是我从 plist 中提取的数据的字典。

Does anyone have an idea of why this would not write to a plist file? It literally does not change the file at all.

有谁知道为什么这不会写入 plist 文件?它实际上根本不会更改文件。

    NSMutableArray *newReports = [[NSMutableArray alloc] init];
    newReports = [[Root objectForKey:@"Reports"] mutableCopy ];

    //Creating data model for new report
    NSMutableDictionary *newReport = [[NSMutableDictionary alloc] init];

    NSString *tempTitle = titleField.text;
    NSString *tempEmployee = employeeField.text;
    NSArray *tempNodes = [[NSArray alloc] init];

    [newReport setObject:tempTitle forKey:@"Title"];
    [newReport setObject:tempEmployee forKey:@"Employee"];
    [newReport setObject:tempNodes forKey:@"Nodes"];

    [newReports addObject:newReport];

    NSMutableDictionary *newRoot = [[NSMutableDictionary alloc] init];

    [newRoot setObject:newReports forKey:@"Reports"];

    //Writing data to plist
    NSString *Path = [[NSBundle mainBundle] bundlePath];
    NSString *filePath = [Path stringByAppendingPathComponent:@"data.plist"];

    [newRoot writeToFile:filePath atomically: YES];

Thanks for the help!

谢谢您的帮助!

回答by Aaron Saunders

try constructing your file path like this

尝试像这样构建您的文件路径

NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectoryPath 
                         stringByAppendingPathComponent:@"data.plist"];
[newRoot writeToFile:filePath atomically: YES]; 

回答by Firoze Lafeer

If you're running this on a device, the main bundle is read only. You'll need to write this plist into the user's documents directory.

如果您在设备上运行它,则主包是只读的。您需要将此 plist 写入用户的文档目录。