在文档目录中创建多个Plist文件..? [英] Creating Multiple Plist files in document directory..?
问题描述
我正在开发一个包含5个 plist
文件的应用程序。我想将所有这些文件保存在文档目录中。因为我想动态地向他们添加数据。我正在使用
I am developing an application which includes 5 plist
files. I want to save all those files in documents directory. Because I want to add data to them dynamically. I am Creating a plist path using
从 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中。我怎么能这样做??
Now I want to add one more plists
in documents directory.. Not in the Bundle. How can i do that..?
推荐答案
以编程方式无法将文件添加到应用程序包中,因为您没有权限并保存或加载 Documents
文件夹中的文件并不是什么大不了的事:
programatically you cannot add files into the application bundle because you don't have permission and to save or load the files from the Documents
folder is not a big deal:
首先,您需要定义文件所在的URL :
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 +
,它从未在模拟器上进行过测试。
this code is working perfectly on any real device with iOS4.3+
, it has never been tested on the simulator.
这篇关于在文档目录中创建多个Plist文件..?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!