Scott Bossak
Scott Bossak

Reputation: 2501

Checking for duplicates when importing to CoreData

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:

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;

}

Upvotes: 0

Views: 1443

Answers (1)

Lorenzo B
Lorenzo B

Reputation: 33428

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.

Upvotes: 3

Related Questions