我正在尝试将一些评论保存在 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 文件写入应用程序的 Documents 或 Application 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/