Search code examples
iosmultithreadingcore-datadispatch-async

iOS Core Data concurrency and other background queues


I am working on a iOS SDK that involves concurrency of Core data. User case is:

  1. App calls SDK's api on the main queue with callback
  2. Core data worker MOC is NSPrivateQueueConcurrencyType. It needs to create model in its queue and save to persistence.
  3. Then, SDK needs to do some lengthy operations in the background, then runs callback on the main queue; or
  4. MOC still needs to update the model in its queue and runs callback on the main queue.

enter image description here

This is my design. By theory, it should work. However, it looks a bit complicated. Is there any other solution?


Solution

  • It might look a bit complicated buy in practice it's probably the simplest and most well structured approach.

    Technically you can use only 2 queues (really threads) and NSConfinementConcurrencyType - assuming that you do only have 1 background thread, which your diagram isn't 100% clear on - but it actually makes your Core Data work a bit more tricky and less obvious. If you always use the private queue context then you know everything operating on the context needs to be in the block and it's easy to see where any errors are.

    If you're going to have multiple background threads all updating the context then your diagram is the easiest option.