jer-k
jer-k

Reputation: 1423

Creating Background Thread for Core Data writing

I'm trying to recreate the three tier core data system that is described in this cocoanetics article ( http://www.cocoanetics.com/2012/07/multi-context-coredata/). The problem I'm running into is creating the private MOC on its own background thread. I don't have much experience with multithreading and how it should be done in objective c. I've been reading over articles and trying to grasp how to correctly implement this approach, but I have finally conceded to the fact that I don't know what I'm doing.

To create this approach, do I need to create an NSThread and manage it? Or is there a simpler way that I'm not understanding?

Upvotes: 4

Views: 1353

Answers (2)

Martin R
Martin R

Reputation: 539755

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.

Upvotes: 5

Ismael
Ismael

Reputation: 3937

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
    });
}

Upvotes: -3

Related Questions