2012-10-08 26 views
0

我已經將新實體添加到現有Plist。由於Plist不一致,新版本的應用程序崩潰。將舊Plist與新Plist合併

如何合併舊plist數據和新plist?

我的plist創作方法如下提前

+0

這是*數據遷移*,它取決於你對plist做什麼。你能否提供更多關於這個plist涉及的內容的信息? – atxe

+0

當然,Plist有一本字典。我添加一個新的'鑰匙'字典。例如:OldDic - > key1 =「aa」key2 =「bb」newDic應該是這樣的newDic - > key1 =「aa」key2 =「bb」key3 =「cc」 – sajaz

回答

0

- (void)createEditableCopyOfFileIfNeeded:(NSString *)plistName 
{ 
    // First, test for existence. 
    BOOL success; 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSError *error; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:plistName]; 
    success = [fileManager fileExistsAtPath:plistPath]; 
    if (success) 
    { 
     return; 
    } 
    // The writable database does not exist, so copy the default to the appropriate location. 
    NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:plistName]; 
    success = [fileManager copyItemAtPath:defaultPath toPath:plistPath error:&error]; 
    if (!success) 
    { 
     NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]); 
    } 
} 

感謝你能做到這樣:

  1. 重命名舊的plist例如old.plist
  2. 從單獨的文件中讀取這兩種的Plist
  3. 合併信息所需的編程選擇添加信息,新的plist
  4. 保存新的plist合併
+0

但我希望在應用程序啓動時發生這種情況 – sajaz

+0

你也可以寫一個簡短的代理類。當它被要求提供信息時,它將確定信息是在舊的還是在新的plist文件中並按需合併。 –

+0

因此,請閱讀啓動時需要的所有信息。您將需要編寫合併類或將它與某些文本合併工具合併。畢竟,你可以在文本上做到這一點 –

2

我會在您的plist到版本關鍵將其與應用程序的版本進行比較。你可以用下面的代碼片段檢查應用程序的版本:

[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] 

然後,在應用程序的啓動:

  1. 閱讀plist中,如果沒有鍵,它會是舊版本
  2. 如果舊版本然後執行數據遷移到當前版本,添加具有默認值的不存在的密鑰。在這裏,我會考慮將來更新的不同版本號。
  3. 添加版本鍵與您的捆綁軟件的版本作爲值。
  4. 保存plist。