在我的应用程序中,我正在通过分页方式从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