你如何异步调用executeFetchRequest?

时间:2014-08-09 22:42:27

标签: ios core-data grand-central-dispatch executefetchrequest

我在IOS应用程序中使用Core Data,并且在获取数据时遇到了瓶颈。我在循环中多次调用executeFetchRequests以每次获取1个结果。每次获取都需要很短的时间,但由于我调用它大约500次,因此获取至少需要一秒钟。我在使用GCD调用executeFetchRequest时遇到问题。

我的代码看起来像这样。 (我删除了保存数据的代码,因为它不是问题)。

设置代码(我不确定这是否应该在线程代码中,它无论如何都不起作用。)

    NSManagedObjectContext *context = [self managedObjectContext];

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity"
                                              inManagedObjectContext:context];

    NSFetchRequest *fetchrequest = [[NSFetchRequest alloc]init];

    [fetchrequest setEntity:entity];

设置GCD内容

    dispatch_group_t x_group = dispatch_group_create();
    dispatch_queue_t x_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

遍历每个谓词

    for (NSPredicate *predicate in arrayOfPredicates) {

        [fetchrequest setPredicate:predicate];    

        dispatch_group_async(x_group, x_queue, ^{

        NSError *error;

        NSArray *array  = [context executeFetchRequest:fetchrequest error:&error];

        for (Entity *managedObject in array) {

            // save stuff to array inside of thread to pass to an array using locks. 

        }    
        });
    }

    dispatch_group_wait(x_group, DISPATCH_TIME_FOREVER);

... more code here...

但是,此代码永远不会超过dispatch_group_wait,并且在使用此方法获取时,获取的managedObject始终为空字符串。如何异步执行此操作,以便延迟时间不长?

1 个答案:

答案 0 :(得分:0)

简短的回答是上下文不是线程安全的。请参阅:Concurrency with Core Data


答案越长,你可能采取了错误的做法。我会设置代码,以便可以使用单个请求获取所有必需的对象:即使我需要更改架构以实现此目的。


更新单谓词的示例

 NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:arrayOfPredicates];
 [fetchrequest setPredicate:predicate];