Search code examples
objective-cmultithreadingcore-datagrand-central-dispatchnsmanagedobjectcontext

CoreData in the background


So I've been using CoreData in the main thread so far. What I want to achieve is create a separate background thread and do ALL CoreData work there. I've read a lot of stuff on CoreData already, but all the background solutions seem more complex than I actually need. The only thing that I need is to be able write and read from CoreData without blocking the UI. I don't care how fast that write or read happens, so if there are 100 reads requests to CoreData let them wait and execute slowly, the main idea is not to block the UI. What would be the best approach to that problem among many CoreData multi-threaded approaches ?

I have all the functionality ready and I just want to make it running on some other thread(but not main). And it is not as easy as just dispatching it on the other thread(cause I tried it)


Solution

  • The simplest thing you could try is to make your main MOC become the child MOC of a private queued background MOC. That will allow -save: to happen on the background. Reads will take the same amount of time. The -save: is a two stage save which you must orchestrate. The first save goes from the main MOC to the background MOC. The second save will push the data to the persistent store while on a background thread.