将对象插入核心数据实体时处理重复项



在我的应用程序中,我使用分页从web服务下载数据。输出是字典的json数组。

现在,我将输出json数组保存在核心数据中。因此,我的问题是,每次使用result数组调用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:

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

使用这些主题ID获取现有主题:

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

获取现有主题ID:

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个对象,因此这应该是完全没有问题的。

最新更新