Updating and changing plist file settings with new versions of the application

I have a default settings plist file in the resources folder of my application and on first start, which is copied to the documents folder.

In future versions of the application, how can I combine the plist settings in my documents with any new keys and values ​​(possibly nested) that were added from the previous version?

I saw a template in which properties are actually created as NSDictionary in the application (with all default settings), and then the current settings saved in the plist file are combined with this dictionary and then saved on top of the current layer.

Is this a good approach? If so, how are you going to combine NSDictionary, which can have multiple nested values ​​with sub-arrays and sub-dictionaries?

Also, is it recommended to have a separate user plist file for settings or to always use NSUserDefaults? Does NSUserDefaults support versioning and changing defaults?

Many thanks,

Mike

+3
source share
1 answer

Ok, I think I came up with a better way to do this:

- (void)readSettings {

    // Get Paths
    NSString *defaultSettingsPath = [[NSBundle mainBundle] pathForResource:@"DefaultSettings" ofType:@"plist"];
    NSString *settingsPath = [self.applicationDocumentsPath stringByAppendingPathComponent:@"Settings.plist"];

    // Read in Default settings
    self.settings = [NSMutableDictionary dictionaryWithContentsOfFile:defaultSettingsPath];

    // Read in Current settings and merge
    NSDictionary *currentSettings = [NSDictionary dictionaryWithContentsOfFile:settingsPath];
    for (NSString *key in [currentSettings allKeys]) {
        if ([[self.settings allKeys] indexOfObject:key] != NSNotFound) {
            if (![[currentSettings objectForKey:key] isEqual:[self.settings objectForKey:key]]) {

                // Different so merge
                [self.settings setObject:[currentSettings objectForKey:key] forKey:key];

            }
        }
    }

}

- (void)saveSettings {
    if (self.settings) {
        NSString *settingsPath = [self.applicationDocumentsPath stringByAppendingPathComponent:@"Settings.plist"];
        [self.settings writeToFile:settingsPath atomically:YES];
    }
}
+1
source

Source: https://habr.com/ru/post/1720823/


All Articles