我的应用程序的资源文件夹中有一个默认设置 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/