2014-03-06 139 views
0

這是我在保存在文檔目錄中的舊陣列1,陣列2是從服務器獲取。在這裏,我必須更新陣列1的各個數據與陣列從服務器上獲取數據後2如何從另一個陣列更新一個陣列

enter image description here

和更新陣列1之後將是:

enter image description here

+0

好吧,那麼你有什麼嘗試?它做錯了什麼? – Wain

回答

0

下面是如何比較兩個數組並更新本地數組的示例。請記住,此代碼可能可以優化,但至少應該給你一個如何去做的想法:-)

- (NSArray *)updateArray:(NSArray *)currentArray withData:(NSArray *)webServerData { 
    NSMutableArray *arr = [[NSMutableArray alloc] init]; 

    //Loop through each NSDictionary in the local array 
    for (NSDictionary *dict in currentArray) { 
     NSString *name = [dict objectForKey:@"NAME"]; 
     BOOL updateDict = NO; 

     //For each NSDictionary, loop through the NSDictionaries in the array from the web server 
     for (NSDictionary *dict2 in webServerData) { 

      //If the name in the local dict is the same as the one in the one from the web server, check if the age is different 
      if ([name isEqualToString:[dict2 objectForKey:@"NAME"]]) { 
       if ([[dict objectForKey:@"AGE"] integerValue] != [[dict2 objectForKey:@"AGE"] integerValue]) { 

        //If the age is different, add the new dictionary 
        [arr addObject:dict2]; 
        updateDict = YES; 
       } 

       break; 
      } 
     } 

     //Add the dict from local array if no new data was found in the web server array 
     if (!updateDict) { 
      [arr addObject:dict]; 
     } 
    } 

    return [arr copy]; 
} 
0

不能寫入plist包含在你的包中。如果您需要plist可編輯,您需要在文檔目錄中創建自己的plist並使用該目錄。

流量:

  1. 在首次啓動時您的應用程序,您可以通過捆綁的plist,以創建一個保存在文檔目錄,從原來的plist內容的新的plist。

  2. 每當您需要plist的數據時,請使用您在啓動時創建並存儲在Documents目錄中的數據。切勿再次使用包中的包。

  3. 當您需要更新plist時,請更新您存儲在文檔中的那個。

+0

我很清楚保存文件並從Doc Dir檢索數據。在這裏,我只需要排序和智能的方式來映射兩個不同的數組,我更新我的問題,可能會幫助你得到我的實際需求。謝謝 – kulss

+0

嗯,所以現在你的問題(如何合併兩個數組與自定義對象)是完全不同於你的原始(如何更新本地plist文件)。你需要做的是遍歷一個數組,並將每個對象與另一個數組中的對象進行比較。如果你的數據結構像草圖,Jorn的答案是一種可能性。我建議你多花一點時間在下一次表達你的問題:-) – Moonwalkr