Creating Background Thread for Core Data writing

情到浓时终转凉″ 提交于 2019-11-30 15:36:45

The easiest way to perform Core Data operations in the background is to create a managed object context of the NSPrivateQueueConcurrencyType. This type of MOC creates and manages a private queue. Using performBlock or performBlockAndWait to execute operations on the private MOC ensures that the right queue is used.

See Concurrency Support for Managed Object Contexts in the Core Data Release Notes for OS X v10.7 and iOS 5.0 for details and examples.

I can only recommend to watch the video or slides from the WWDC 2011 Session 303 "What’s New in Core Data on iOS", where Core Data concurrency is explained.

Managing threads is very basic in iOS

To have something run on background, you do like this:

- (void)someMethod {
    // method is called on main thread normally

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        .... // here things are run in background
    });
}

To go back to main thread anywhere, do this:

- (void)someOtherMethod {
    // method is called on background thread

    dispatch_async(dispatch_get_main_queue(), ^{
        ... // here things are on main thread again
    });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!