Search code examples
iosnsdictionaryplist

writeToFile NSDictionary not saving to plist correctly


I have a custom plist that I am using to populate UItableViewCells with, I am able to read them perfectly, however when I try to write to my custom plist file it never changes.

NSString *errorDesc = nil;
NSString * plistPath = [[NSBundle mainBundle] pathForResource:@"AdvanceSearchPrefrences" ofType:@"plist"];
NSMutableDictionary *advPrefs = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
[advPrefs setObject:cell.textLabel.text forKey:@"Manuf"];
[advPrefs setObject:selRow forKey:@"ManufNum"];
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:advPrefs format:NSPropertyListXMLFormat_v1_0 errorDescription:&errorDesc];
[plistData writeToFile:plistPath atomically:YES];


NSString * plistPath2 = [[NSBundle mainBundle] pathForResource:@"AdvanceSearchPrefrences" ofType:@"plist"];
NSMutableDictionary *advPrefs2 = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath2];

The advPrefs shows the new values and advPrefs2 shows the old values.


Solution

  • You can't directly save over your plist, but what you can do is create a copy and save that to NSUserDefaults.

    On the initial load you do something like this in your AppDelegate. This will copy your plist into something you can edit and save:

        NSString * plistPath = [[NSBundle mainBundle] pathForResource:@"AdvanceSearchPrefrences" ofType:@"plist"];
        NSMutableDictionary *advPrefs = [NSDictionary dictionaryWithContentsOfFile:plistPath];
        [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:advPrefs] forKey:@"plist"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    

    In your class that you want to fetch the copied plist, you can call something like this:

        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSData *data = [defaults objectForKey:@"plist"];
        NSMutableDictionary *advPrefs = [[NSKeyedUnarchiver unarchiveObjectWithData:data]mutableCopy];
    

    Then make your changes

        [advPrefs setObject:cell.textLabel.text forKey:@"Manuf"];
        [advPrefs setObject:selRow forKey:@"ManufNum"];
    

    And then save them to NSUserDefaults

        [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:advPrefs] forKey:@"plist"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    

    I had this same problem with my app and this is how I fixed it. Hope this works for you too