【发布时间】:2012-07-26 11:54:39
【问题描述】:
我正在尝试将一些 cmets 保存在 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:]: index (1) beyond bounds (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”。我已经检查了权限
【问题讨论】:
-
异常发生时发布stacktrace。
-
这不是堆栈跟踪。堆栈跟踪可让您查看当代码崩溃时您在代码中的位置。
-
已经弄明白了。编写代码不起作用,我只是不知道为什么
标签: objective-c ios plist nsdictionary