更新和更改设置plist文件与新版本的应用程序
问题描述:
我有一个默认设置plist文件在我的应用程序的资源文件夹,并在第一次启动时被复制到文档文件夹。更新和更改设置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];
}
}
'为(的NSString *在关键[currentSettings allKeys]) '可以写为'for(NSString * key in currentSettings)'。 'if([[self.settings allKeys] indexOfObject:key]!= NSNotFound)'可以写成'if([self.settings objectForKey:key])' – user102008 2011-01-18 23:08:58