2015-12-16 69 views
0

在我的應用程序中,我正在通過分頁方式從Web服務下載數據。輸出是一個由字典組成的json數組。將對象插入核心數據實體時處理重複

現在,我將輸出json數組保存在覈心數據中。所以,我的問題是,每次使用結果數組調用saveInCoreData:方法時,它會在數據庫中創建重複的對象。我如何檢查對象並更新或替換對象,如果它已經存在? myId是一個uniq鍵。

// save in coredata 
+ (void) saveInCoreData:(NSArray *)arr{ 

// get manageObjectContext 
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 

NSManagedObjectContext *context = [appDelegate managedObjectContext]; 

if(arr != nil && arr.count > 0) { 

    for(int i=0; i < arr.count; i++){ 

     SomeEntity *anObj = [NSEntityDescription 
           insertNewObjectForEntityForName:@"SomeEntity" 
           inManagedObjectContext:context]; 


     anObj.description = [[arr objectAtIndex:i] objectForKey:@"description"]; 
     anObj.count = [NSNumber numberWithInteger:[[[arr objectAtIndex:i] objectForKey:@"count"] integerValue]]; 

     // Relationship 
     OtherEntity *anOtherObject = [NSEntityDescription 
            insertNewObjectForEntityForName:@"OtherEntity" 
            inManagedObjectContext:context]; 
     creatorDetails.companyName = [[[arrTopics objectAtIndex:i] objectForKey:@"creator"] objectForKey:@"companyName"]; 
    } 
} 
+0

假設您正在添加具有屬性,名稱,ID,拍攝日期,位置等的照片。讓「ID」爲所有照片中唯一的屬性,如果是這種情況,只需在xcdatamodeld中選擇您的照片實體並在在Constraints選項卡中的Inspector窗口中,輸入該屬性名稱,即所有,現在,當您執行保存時,Core Data將驗證其唯一性,並且您將只獲得該實例的一個實例。 – Alok

回答

2

最有效的方法,以避免重複是獲取你已經擁有的所有對象,並遍歷結果時,避免處理它們。

從結果中獲取topicIds:

NSArray *topicIds = [results valueForKeyPath:@"topicId"]; 

取現有的主題與這些topicIds:

NSFetchRequest *request = ...; 
request.predicate = [NSPredicate predicateWithFormat:@"%K IN %@", 
           @"topicId", topicIds]; 
NSArray *existingTopics = [context executeFetchRequest:request error:NULL]; 

獲取現有topicIds:

NSArray *existingTopicIds = [existingTopics valueForKeyPath:@"topicId"]; 

過程的結果:

for (NSDictionary *topic in results) { 
    if ([existingTopicIds containsObject:topic[@"topicId"]]) { 
     // Update the existing topic if you want, or just skip. 

     continue; 
    } 

    ... 
} 

試圖單獨地提取每個現有主題,則處理循環中,將在時間上非常低效的。權衡是更多的內存使用情況,但由於您一次只能獲得20個對象,因此這應該是一個完全沒有問題的問題。

+0

感謝您的詳細解答 – sajaz