开发者

writing NSArray back to plist

I have a plist with the following format:

writing NSArray back to plist

And here's how I read it:

NSString *errorDesc = nil;
    NSPropertyListFormat format;

    NSString *path = [[NSBundle mainBundle] pathForResource:@"States" ofType:@"plist"];    
    NSData 开发者_C百科 *plistXML = [[NSFileManager defaultManager] contentsAtPath:path];
    NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization                     
                                          propertyListFromData:plistXML
                                          mutabilityOption:NSPropertyListMutableContainersAndLeaves
                                          format:&format
                                          errorDescription:&errorDesc];

    self.statesData = [temp objectForKey:@"Root"];

The question is if I want to write this NSMutableArray called self.statesData back to the plist, how would I do it? I am guessing something like this wouldn't work...

 NSString *path = [[NSBundle mainBundle] pathForResource:@"States" ofType:@"plist"];  
    [self.main.statesData writeToFile:path atomically: YES];


You can not write the app's bundle, you need to write to the app's Document directory.

Sample code:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];

BOOL status = [array writeToFile:filePath atomically:YES];

If you have initial dad in the app bundle on first run copy it to the Documents directory and make all further accesses to the Documents directory.


On iOS, you can't write to files in your app wrapper (and on MacOS X, you really shouldn't). What you need to do is first copy to the Documents folder from the app wrapper, then load and save to that version.

Getting the Documents folder:

NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
;
filePath = [filePath stringByAppendingPathComponent:@"States.plist"];
[self.statesData writeToFile:path atomically:YES];

Loading the file from the app wrapper you are already doing; copying can be done readily using NSFileManager. You can reconstitute the temp array and replace the key from your statesData before saving. An alternate read command might be:

self.statesData = [NSArray arrayWithContentsOfFile:filePath];


SWIFT version of @zaph's code above:

let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let documentsDirectory = paths[0]
let filePath = NSURL(fileURLWithPath: documentsDirectory, isDirectory: true).URLByAppendingPathComponent(fileName)
let status = items.writeToFile(filePath.absoluteString, atomically: true)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜