【发布时间】:2014-08-09 22:42:26
【问题描述】:
我在 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 始终是一个空字符串。我怎样才能异步执行此操作,以便没有很长的延迟期?
【问题讨论】:
-
[context performBlock:^ { /* Create & execute your NSFetchRequest here */ }];将以线程安全的方式异步执行您的获取请求。 Jeffery Thomas 列出的“Concurrency with Core Data”文档有更详细的信息。 -
为什么要循环播放?请展示你在做什么——这几乎可以肯定地在不循环获取请求的情况下完成。
标签: ios core-data grand-central-dispatch executefetchrequest