我试图在plist中保存一些评论,这没关系,因为它只是一个原型。问题是我可以从plist读取,但是当我尝试写入和读取之后,它会抛出一个“数组越界”异常。我无法弄清楚我在这里做错了什么。如何在.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];
回报是(空)
但是如果我使用:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Comments" ofType:@"plist"];
NSMutableArray *plistArray = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
我可以看到数组的内容以及它的所有工作正常。
问题是:在两种方式我不能写入文件,它不断返回“否”。而且我已经检查的权限
发生异常时发送堆栈跟踪。 – trojanfoe 2012-07-26 11:55:54
@trojanfoe发布 – 2012-07-26 12:17:48
这不是一个堆栈跟踪。一个stacktrace可以让你看到你的代码在崩溃的时候在哪里。 – trojanfoe 2012-07-26 12:21:41