【发布时间】:2015-12-16 11:02:58
【问题描述】:
在我的应用程序中,我通过分页从 Web 服务下载数据。输出是一个 json 字典数组。
现在,我将输出 json 数组保存在核心数据中。所以,我的问题是,每次使用结果数组调用 saveInCoreData: 方法时,它都会在数据库中创建重复的对象。如果对象已经存在,我如何检查对象并更新或替换该对象? myId 是唯一键。
// 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 和 Inspector 窗口的 Constraints 选项卡中,输入该属性名称,仅此而已,现在当您执行保存时,Core Data 将验证它的唯一性,您将只获得一个实例。
标签: ios objective-c json core-data