在导入CoreData时检查重复项 [英] Checking for duplicates when importing to CoreData

查看:258
本文介绍了在导入CoreData时检查重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用RestKit将数据导入Core Data存储,需要检查重复项。如果该项目已经在商店中,我想更新它的最新属性。如果是新项目,我想创建它。

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.

导入很慢,所以我使用Instruments,看到最长的导入部分是检查该项目已经存在(有一个fetch请求)

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:


  • 使用countForFetchRequest查看该项目是否已存在,然后使用executeFetchRequest返回要更新的项目或

  • 只要executeFetchRequest取得要更新的项目

  • 或是有更好的方法吗?

我认为countForFetchRequest会更快,因为整个NSManagedObject不会返回,只有执行fetch请求,如果我知道将有一个NSManagedObject。

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.

谢谢

- (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;

}

推荐答案

apple.com/library/ios/#documentation/cocoa/conceptual/CoreData/Articles/cdImporting.htmlrel =nofollow>实施有效查找或创建。

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.

显然,你应该在后台进行工作,防止主线程冻结,使用线程限制或新的iOS核心数据队列API。

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

希望有帮助。

这篇关于在导入CoreData时检查重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆