Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing NSArray back to plist

I have a plist with the following format:

enter image description here

And here's how I read it:

NSString *errorDesc = nil;
    NSPropertyListFormat format;

    NSString *path = [[NSBundle mainBundle] pathForResource:@"States" ofType:@"plist"];    
    NSData  *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];
like image 745
xonegirlz Avatar asked Jun 09 '26 15:06

xonegirlz


1 Answers

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.

like image 64
zaph Avatar answered Jun 11 '26 04:06

zaph