Mads Lee Jensen
Mads Lee Jensen

Reputation: 4648

iOS saving main thread NSManagedObjectContext changes in background

Im trying to figure out right now all my core data is managed on the main thread, with a single context. I used instrument and noticed the save operations are blocking the main thread for quite some time. I would like to run my save operations on a background thread using GCD

Now i understand how to setup this process with creating a new thread / context and listen for "save" notifications to merge back on the main thread.

But when i create a new context all the changes from the main thread's context needs to be inserted / merged into the new, else it wont have anything to save?? i can seem to find any examples for this.

For example on my main context ive:

now how do i make my background context know if these changes?

Would it make sense to create the background context right when the application starts and have it listen for NSManagedObjectContextObjectsDidChangeNotification on the main thread to constantly keep it in sync??

Upvotes: 1

Views: 1943

Answers (2)

svena
svena

Reputation: 2779

In iOS5 you can do this easily with new concurrency types. If you create a context with NSPrivateQueueConcurrencyType, you will not block the main thread. But you have to access the context inside your block passed in to managedObjectContext:performBlock method.

Upvotes: 1

Adam
Adam

Reputation: 26907

You can't pass NSManagedObject instances between threads. If you are struggling with large datasets you might want to read this post by Marcus Zarra.

Upvotes: 0

Related Questions