iphone - 使用新版本的应用程序更新和更改设置 plist 文件

标签 iphone settings plist nsdictionary nsuserdefaults

我的应用程序的资源文件夹中有一个默认设置 plist 文件,首次启动时该文件会复制到文档文件夹中。

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

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

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

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

非常感谢,

迈克

最佳答案

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

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

关于iphone - 使用新版本的应用程序更新和更改设置 plist 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1609305/

相关文章:

ios - 在 Xcode Swift 3 中使用约束时水平 slider 消失

java - 共享首选项修改mapView的 View

visual-studio-code - 如何更改vs代码中关键字的颜色(setting.json)

objective-c - cocoa 用户界面分析

ios - iOS中pathForResource为空

iphone - 静态数据的属性列表或 sqlite?

ios - 应用程序崩溃没有任何错误

iphone - 是否可以从 iPhone safari 浏览器获取 UDID?

iphone - 显示 UINavigationBar 后退按钮而不按下 View Controller

Android - 在用户启用输入法后关闭 IME 设置 Activity