Checking for duplicates when importing to CoreData

孤人 提交于 2019-12-02 16:26:09

问题


I'm importing data into a Core Data store using RestKit and need to check for duplicates. If the item is already in the store, I'd like to update it with the latest attributes. If it's a new item, I'd like to create it.

The import was slow so I used Instruments and saw that the longest part of importing was checking to see if the item already exists (with a fetch request)

So I'd like to know if checking to see if the item is already in the store, is it faster to:

  • use countForFetchRequest to see if the item already exists, then executeFetchRequest to return the item to update or
  • just executeFetchRequest to get the item to update
  • or is there a better way to do this?

I thought countForFetchRequest would be faster since the entire NSManagedObject isn't returned and only execute the fetch request if I know there's going to be a NSManagedObject.

Thanks

- (Product *)productWithId:(int)productID {

    NSManagedObjectContext *context = [Model sharedInstance].managedObjectContext;
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"product_id == %d", productID];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = [NSEntityDescription entityForName:@"Product" inManagedObjectContext:context];
    request.predicate = predicate;
    request.fetchLimit = 1;

    NSError *error = nil;

    NSUInteger count = [context countForFetchRequest:request error:&error];

    if (!error && count == 1) {
        NSArray *results = [context executeFetchRequest:request error:&error];
        if (!error && [results count]) {
            return [results objectAtIndex:0];
        }
        return nil;
    }

    return nil;

}


回答1:


As far I know, the best way to find and/or import objects within Core Data is described in Implementing Find-or-Create Efficiently.

The documentation describes a find or create pattern that it's based on sorting data: the data you download from the service and the data you grab form the store.

I really suggest you to read the link I provided. You will see a speed up on your performances.

Obviously you should do the work in background, preventing the main thread to freeze, using thread confinement or new iOS Core Data queue API.

Hope that helps.



来源:https://stackoverflow.com/questions/12415564/checking-for-duplicates-when-importing-to-coredata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!