objective-c - 如何在.plist中写入数据?

标签 objective-c ios plist nsdictionary

我正在尝试将一些评论保存在 plist 中,这没关系,因为它只是一个原型(prototype)。问题是我可以从 plist 中读取,但是当我尝试之后写入和读取时,它会抛出“数组越界”异常。我不明白我在这里做错了什么。

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Comments" ofType:@"plist"];
NSMutableArray *plistArray = [[NSMutableArray alloc] initWithContentsOfFile:filePath];


NSMutableDictionary *newComment = [NSMutableDictionary dictionary];
[newComment setValue:commentTitle.text forKey:@"title"];
[newComment setValue:comment forKey:@"comment"];


[plistArray addObject:newComment];
[plistArray writeToFile:filePath atomically:NO];

效果很好,然后我尝试阅读:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Comments" ofType:@"plist"];
NSMutableArray *plistArray = [[NSMutableArray alloc] initWithContentsOfFile:filePath];


NSMutableDictionary *dictionary = (NSMutableDictionary *) [plistArray objectAtIndex:0];

NSLog(@"%@", [dictionary objectForKey:@"title"]);

它会抛出异常。

如果我手动将项目添加到 plist,它工作正常,我想这意味着我的阅读代码没问题。

这可能是我的plist的结构吗?

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
 <plist version="1.0">
 <array>
 </array>
 </plist>

* 由于未捕获的异常“NSRangeException”而终止应用程序,原因:“-[__NSCFArray objectAtIndex:]:索引 (1) 超出界限 (1)”

在写入 plist 之前,我将“描述”添加到数组中。如果我使用以下代码:

NSString *aDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//    NSString *aFilePath = [NSString stringWithFormat:@"%@/Comments.plist", aDocumentsDirectory];
//
//    NSMutableArray *plistArray = [[NSMutableArray alloc] initWithContentsOfFile:aFilePath];

返回值为(null)

但是如果我使用:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Comments" ofType:@"plist"];
NSMutableArray *plistArray = [[NSMutableArray alloc] initWithContentsOfFile:filePath];

我可以看到数组的内容,并且一切正常。

问题是:在这两种方式中我都无法写入文件,它一直返回“NO”。我已经检查了权限

最佳答案

您正在尝试将文件写入mainBundle。绝对不可能。 您必须将 plist 文件写入应用程序的 DocumentsApplication Support 文件夹。

在文档目录中创建文件路径:

NSString *aDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

NSString *aFilePath = [NSString stringWithFormat:@"%@/Comments.plist", aDocumentsDirectory];

写入文件路径

[plistArray writeToFile:aFilePath atomically:YES];

从文件路径读取

NSMutableArray *plistArray = [[NSMutableArray alloc] initWithContentsOfFile:aFilePath];

关于objective-c - 如何在.plist中写入数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11668733/

相关文章:

ios - 使用自定义字体而不包含在info.plist ios中

ios - 在第一个 View Controller 中完成某些操作后,在第二个 View Controller 中重新加载数据

swift - 将快速字典写入文件

objective-c - 不使用时自动隐藏工具栏

iphone - UIButton 不更改标题

ios - 使用数字格式化程序指定文本字段中的小数位数

ios - 来自 NSTableViewCell 的 titleForHeaderSection

objective-c - 在 plist 中更新和保存数据

iphone - 在 FTP 上上传多个文件

ios - 我如何重新填充 TableView Controller ?