我在IOS应用程序中使用核心数据,在获取数据时遇到瓶颈。我在一个循环中多次调用executeFetchRequests,每次获取一个结果。每次抓取都需要很短的时间,但是因为我调用了大约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始终是一个空字符串。我如何异步地做这件事,这样才不会有很长的延迟期?
发布于 2014-08-10 06:57:24
简而言之,上下文不是线程安全的。请参阅:Concurrency with Core Data
更长的答案是,你可能有错误的方法。我会设置代码,以便可以使用单个请求获取所有需要的对象:即使我需要更改模式才能做到这一点。
单谓词的更新示例
NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:arrayOfPredicates];
[fetchrequest setPredicate:predicate];https://stackoverflow.com/questions/25223801
复制相似问题