2009-10-22 46 views
3

我有一個默認設置plist文件在我的應用程序的資源文件夾,並在第一次啓動時被複制到文檔文件夾。更新和更改設置plist文件與新版本的應用程序

在應用程序的後續版本中,如何將文檔中的plist設置與自上一版本以來添加的任何新鍵&值(可能是嵌套的)合併?

我見過一種模式,其中的屬性實際上是作爲應用程序中的NSDictionary創建的(具有所有默認設置),然後保存在plist文件中的當前設置與該字典合併,然後保存目前的plist。

這是一個很好的方法嗎?如果是這樣,你怎麼去合併可能有幾個嵌套值的NSDictionary與子數組和子字典?

此外,它是否建議有一個單獨的自定義plist文件的設置,或者你應該總是使用NSUserDefaults? 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]; 
    } 
} 
+0

'爲(的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

相關問題