使用 CoreData 的 Grand Central Dispatch (GCD) [英] Grand Central Dispatch (GCD) with CoreData

查看:20
本文介绍了使用 CoreData 的 Grand Central Dispatch (GCD)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序中使用 Grand Central Dispatch (GCD) 来完成一些繁重的工作.该应用程序使用 Core-Data 进行数据存储.这是我的场景(以及相关问题):

I'm using Grand Central Dispatch (GCD) in my application to do some heavy lifting. The application is using Core-Data for data storage purposes. Here's my scenario (along with relevant question):

dispatch_queue_t main_queue = dispatch_get_main_queue();
dispatch_queue_t request_queue = dispatch_queue_create("com.app.request", NULL);

dispatch_async(request_queue, ^{
    MyNSManagedObject *mObject = [self.fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];

    // … 
    // <heavy lifting>
    // … 

    // … 
    // <update mObject>
    // … 

    [self saveManagedObjectContext];
});     

作为 [self saveManagedObjectContext] 的结果,fetchResultsController 委托方法被自动调用.因此,UI 更新逻辑开始了.

As a result of [self saveManagedObjectContext], fetchResultsController delegate methods are called automatically. Consequently, the UI updation logic kicks.

现在我的问题是,我需要为 -saveManagedObjectContext 使用 main_queue 吗?我应该对 main_queue 中的 NSManagedObject 执行所有操作吗?某些更新 NSManagedObject 的操作可能需要 2-3 秒.请指教.

Now my question is, do I need to use main_queue for -saveManagedObjectContext? Should I perform all operations on my NSManagedObject in main_queue? Some of the operations that update the NSManagedObject might take 2-3 seconds. Please advise.

推荐答案

您可能知道或已经注意到,您必须在主线程上执行 UI 操作.正如您所提到的,这是在您保存 UI 更新时发生的.您可以通过在主线程上嵌套调用 dispatch_sync 来解决此问题.

As you probably know or have noticed you must perform UI operations on the main thread. As you mention it is when you save the UI update takes place. You can solve this by nesting a call to dispatch_sync on the main thread.

dispatch_queue_t main_queue = dispatch_get_main_queue();
dispatch_queue_t request_queue = dispatch_queue_create("com.app.request", NULL);

__block __typeof__(self) blockSelf = self;

dispatch_async(request_queue, ^{
    MyNSManagedObject *mObject = [blockSelf.fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];

    // update and heavy lifting...

    dispatch_sync(main_queue, ^{
      [blockSelf saveManagedObjectContext];
    });
});     

使用 blockSelf 是为了避免意外创建引用循环. (实用块)

这篇关于使用 CoreData 的 Grand Central Dispatch (GCD)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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