【问题标题】:Updating & changing settings plist files with new versions of an app使用新版本的应用程序更新和更改设置 plist 文件
【发布时间】:2010-12-09 05:17:43
【问题描述】:

我的应用程序的资源文件夹中有一个默认设置 plist 文件,并且在第一次启动时被复制到文档文件夹中。

在应用程序的后续版本中,如何将其文档中的 plist 设置与自上一版本以来添加的任何新键和值(可能是嵌套的)合并?

我看到了一种模式,其中属性实际上是在应用程序中创建为 NSDictionary(使用所有默认设置),然后保存在 plist 文件中的当前设置与该字典合并,然后保存在当前列表。

这是一个好方法吗?如果是这样,您如何将可能具有多个嵌套值的 NSDictionary 与子数组和子字典合并?

另外,是否建议使用单独的自定义 plist 文件进行设置,还是应该始终使用 NSUserDefaults? NSUserDefaults 是否处理版本控制和更改默认值?

非常感谢,

迈克

【问题讨论】:

    标签: iphone settings plist nsdictionary nsuserdefaults


    【解决方案1】:

    好的,我想我已经想出了最好的方法:

    - (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];
        }
    }
    

    【讨论】:

    • for (NSString *key in [currentSettings allKeys]) 可以写成for (NSString *key in currentSettings)if ([[self.settings allKeys] indexOfObject:key] != NSNotFound) 可以写成if ([self.settings objectForKey:key])
    猜你喜欢
    • 2013-02-18
    • 1970-01-01
    • 2010-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-06
    • 2018-10-14
    • 1970-01-01
    相关资源
    最近更新 更多