无法写入Plist

时间:2011-02-25 11:44:56

标签: iphone plist

我有一个关于如何写一个plist的非常基本的问题。我在我的资源文件夹中添加了一个“Here.plist”文件。以下是我的代码:

NSString *path = [[NSBundle mainBundle]pathForResource:@"Here" ofType:@"plist"];

NSArray *array = [[NSArray alloc]initWithObjects:@"First", @"Second", @"Third", nil];

[array writeToFile:path atomically:YES];

执行代码后,“Here.plist”仍为空。我甚至尝试使用NSDictionary如下:

NSDictionary *dict = [[NSDictionary alloc]initWithObjectsAndKeys:@"firstValue", @"First", @"secondValue", @"Second", @"thirdValue", @"Third", nil];

[dict writeToFile:path atomically:YES];

我经历了很多教程和论坛,但它不适合我。我究竟做错了什么?我不知所措。

2 个答案:

答案 0 :(得分:7)

您无法写入捆绑包。尝试写入文档目录。例如:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *array = [[NSArray alloc]initWithObjects:@"First", @"Second", @"Third", nil];
[array writeToFile:[documentsDirectory stringByAppendingPathComponent:@"Here.plist" atomically:YES];

答案 1 :(得分:2)

我怀疑您的问题是由于您无法写入应用程序包,只能写入应用程序的文档存储区。

要获取文档存储的路径,请使用:

NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docStorePath = [searchPaths objectAtIndex:0];

NSString *filePath = [docStorePath stringByAppendingPathComponent:@"XXXXX"];