Using Core Data Concurrently and Reliably

后端 未结 4 764
感动是毒
感动是毒 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:29

    NSFetchedResultsController has been proven to be a bit sensitive to massive deletes so that is where I would start digging first.

    My initial question is, how are the re-fetch and reload of tableview related to the start of delete operation. Is there a chance that the deletion block will save child MOC while the NSFetchedResultsController is still fetching or no?

    Is it possible that when you switch from detail view to master and then back to detail view there will be multiple concurrent background tasks running? Or are you retrieving all the data from the web service at once not only that relevant to a particular row?

    One alternative to make this more robust is to use a pattern similar to what UIManagedDocument uses:

    Instead of using a parent MOC as Main Thread concurrency type, UIManagedDocument actually creates the main MOC as private queue and makes the child MOC available to you use on the main thread. The benefit here is that all the I/O goes on in the background and saves to the parent MOC does not interfere with the child MOC at all until child MOC is explicitly made know about them. That's because save commits changes from child to parent and not the other way around.

    So if you did your deletes on a parent queue which is private, that would not end up in the NSFetchedResultsController scope at all. And since it is old data, that is actually the preferred way.

    An alternative I offer is to use three contexts:

    Main MOC (NSPrivateQueueConcurrencyType)

    • Responsible for persistent store and deletion of old data.

    Child MOC A (NSMainQueueConcurrencyType)

    • Responsible for anything UI related and NSFetchedResultsController

    Child MOC B (NSPrivateQueueConcurrencyType, child of Child MOC A)

    • Responsible for inserting new data and committing it up to Child MOC A when done.

提交回复
热议问题