hectr / MRFetchedResultsController

Extensible drop-in replacement for NSFetchedResultsController.
MIT License
5 stars 4 forks source link

Insert called twice in MRFetchedResultsControllerDelegate when using MagicalRecord's mr_saveToPersistentStoreAndWait #1

Open mludowise opened 7 years ago

mludowise commented 7 years ago

I'm attempting to convert my code from using NSFetchedResultsController to MRFetchedResultsController in order to support OS X 10.11.

When switching my code over, I noticed a bug where when I was calling NSManagedObjectContext.mr_default().mr_saveToPersistentStoreAndWait(), that my MRFetchedResultsControllerDelegate getting the controller didChange method called twice in a row with a ChangeType of .insert. My fetchedResultsController is using the NSManagedObjectContext.mr_default() as its context.

However, when I change my fetchedResultsController to instead use NSManagedObjectContext.mr_rootSaving(), then it only gets called once. This isn't ideal since this context exists in a background thread and I had to wrap the contents in my controller didChange, controllerWillChangeContent(), and controllerDidChangeContent() methods in a DispatchQueue.main.async since I was making UI updates.

It seems to only happen for insert as far as I can tell.

P.S. I'm using Swift but happy to try to translate to objective-c syntax if that's easier.

hectr commented 7 years ago

If NSManagedObjectContext.mr_rootSaving() is being notified as expected, instead of wrapping delegate methods in a DispatchQueue.main.async, you could set MRFetchedResultsController's notifyChangesQueue property. And MRFetchedResultsController will notify its delegate in the queue you set.

I've never identified the malfunction you are experiencing. I wonder if it has something to do with MagicalRecord's Core Data stack or if it can be reproduced in any other set up 🤔

You could set MRFetchedResultsController's changesAppliedOnSave property. It will make MRFetchedResultsController listen to NSManagedObjectContextDidSaveNotification instead of NSManagedObjectContextObjectsDidChangeNotification. Which I would expect to be called only once.