问题
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
Retrieving data from 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];
Writing data to plist
scorePlistPath = [docpath stringByAppendingPathComponent:@"highScores.plist"];
[highScoreArray writeToFile:scorePlistPath atomically:YES];
Now I want to add one more plists
in documents directory.. Not in the Bundle. How can i do that..?
回答1:
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:
first, you need to define the URL where the file is:
NSString *_filename = @"myOwn.plist";
NSURL *_resourceURL = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] URLByAppendingPathComponent:_fileName];
then you can save the file:
NSArray *_array = // your array as you defined
[_array writeToURL:_resourceURL atomically:true];
and anytime the file can be loaded again:
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
and violá, it is done.
UPDATE #1
this code is working perfectly on any real device with iOS4.3+
, it has never been tested on the simulator.
来源:https://stackoverflow.com/questions/11559639/creating-multiple-plist-files-in-document-directory