borrrden
borrrden

Reputation: 33421

Clarification about Multithreaded Core Data

I understand in general that Core Data is not thread safe, but I have a question about a specific situation. Let's say I create an object in a context on the main thread, but then I want to do some heavy calculations. So I send the object over to another thread. This sounds bad already, do I need to copy that object somehow? If I save the object in a context on the other thread, then it seems that it fails to get a valid object out of that context (do I have to save to the store first? This seems like an abuse of the hard disk). I am using Magical Record at the moment and the flow is something like this:

mSaveData = [XXX MR_createEntity];
//Set various properties

//In another method
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    mSaveData.questionId = xxx;
    //Set more properties

    [[mSaveData managedObjectContext] MR_saveToPersistentStoreAndWait];
}

At first I thought I should be using [mSaveData MR_inThreadContext] but this method returns nil (maybe because the object has not been saved yet?). My current approach shares a context between threads (just for the save operation) so it makes me a bit uncomfortable. Is there a different approach that is preferred? Should I simply dispatch back to the main thread to set the properties and save?

Upvotes: 1

Views: 143

Answers (1)

Gary
Gary

Reputation: 5732

Please go and read the documentation. You cannot share contexts or managed objects between threads.

You can pass an object id to another thread and retrieve the associated object from that thread's context.

  1. Save the context in the first thread.
  2. Use the contextDidSave notification to merge the changes into the context in the second thread.
  3. You will then be able to retrieve the up to date object in the second thread.

Upvotes: 2

Related Questions