在文档目录中创建多个Plist文件..?

时间:2012-07-19 11:13:21

标签: iphone objective-c ios5 plist

我正在开发一个包含5个plist文件的应用程序。我想将所有这些文件保存在文档目录中。因为我想动态地向他们添加数据。我正在使用

创建一个plist路径

plist

中检索数据
NSMutableArray *pathsArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docpath = [pathsArray objectAtIndex:0];
NSString *scorePlistPath = [docpath stringByAppendingPathComponent:@"highScores.plist"];

if (![[NSFileManager defaultManager] fileExistsAtPath:scorePlistPath]) {
    scorePlistPath = [[NSBundle mainBundle] pathForResource:@"highScores" ofType:@"plist"];
}
highScoreArray = [[NSMutableArray alloc]initWithContentsOfFile:scorePlistPath];

将数据写入plist

scorePlistPath = [docpath stringByAppendingPathComponent:@"highScores.plist"];

[highScoreArray writeToFile:scorePlistPath atomically:YES];

现在我想在文档目录中再添加一个plists ..不在Bundle中。我怎么能这样做..?

1 个答案:

答案 0 :(得分:0)

以编程方式无法将文件添加到应用程序包中,因为您没有权限并且保存或加载Documents文件夹中的文件并不是一件大事:

首先,您需要定义文件所在的网址

NSString *_filename = @"myOwn.plist";
NSURL *_resourceURL = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] URLByAppendingPathComponent:_fileName];

然后您可以保存文件

NSArray *_array = // your array as you defined
[_array writeToURL:_resourceURL atomically:true];

并且可以在任何时候再次加载文件

NSData *_plistData = [NSData dataWithContentsOfFile:[_resourceURL path]];
NSArray *_loadedArray = [NSPropertyListSerialization propertyListFromData:_plistData mutabilityOption:NSPropertyListImmutable format:nil errorDescription:nil]; // the option or the format parameter might be set for your special wishes, so check the documentation, please

violá,已经完成。

更新#1

此代码适用于任何带有iOS4.3+真实设备,它从未在模拟器上进行过测试。

相关问题