大中央调度(GCD)与CoreData [英] Grand Central Dispatch (GCD) with CoreData

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

问题描述

我在我的应用程序中使用大中央调度(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.

现在我的问题是,我需要使用 main_queue c $ c> -saveManagedObjectContext ?我应该对 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 是为了避免创建意外的引用循环。实用块

这篇关于大中央调度(GCD)与CoreData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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