简体   繁体   中英

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:

  • inserted 2x users
  • deleted 3 wallposts
  • updated some friend relationships.

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??

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM