Using Core Data Concurrently and Reliably

后端 未结 4 762
感动是毒
感动是毒 2021-02-06 08:41

I\'m building my first iOS app, which in theory should be pretty straightforward but I\'m having difficulty making it sufficiently bulletproof for me to feel confident submittin

4条回答
  •  独厮守ぢ
    2021-02-06 09:28

    Pre-iOS 5, we've usually had two NSManagedObjectContexts: one for the main thread, one for a background thread. The background thread can load or delete data and then save. The resulting NSManagedObjectContextDidSaveNotification was then passed (as you're doing) to the main thread. We called mergeChangesFromManagedObjectContextDidSaveNotification: to bring those in to the main thread context. This has worked well for us.

    One important aspect of this is that the save: on the background thread blocks until after the mergeChangesFromManagedObjectContextDidSaveNotification: finishes running on the main thread (because we call mergeChanges... from the listener to that notification). This ensures that the main thread managed object context sees those changes. I don't know if you need to do this if you have a parent-child relationship, but you did in the old model to avoid various kinds of trouble.

    I'm not sure what the advantage of having a parent-child relationship between the two contexts is. It seems from your description that the final save to disk happens on the main thread, which probably isn't ideal for performance reasons. (Especially if you might be deleting a large amount of data; the major cost for deletion in our apps has always happened during final save to disk.)

    What code are you running when the controllers appear/disappear that could be causing core data trouble? What kinds of stack traces are you seeing the crash on?

提交回复
热议问题