在我的應用程序中,我正在通過分頁方式從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"];
}
}
假設您正在添加具有屬性,名稱,ID,拍攝日期,位置等的照片。讓「ID」爲所有照片中唯一的屬性,如果是這種情況,只需在xcdatamodeld中選擇您的照片實體並在在Constraints選項卡中的Inspector窗口中,輸入該屬性名稱,即所有,現在,當您執行保存時,Core Data將驗證其唯一性,並且您將只獲得該實例的一個實例。 – Alok