magicalpanda / MagicalRecord

Super Awesome Easy Fetching for Core Data!
Other
10.79k stars 1.79k forks source link

One save causes two NSManagedObjectContext updates (twice)? #618

Closed mgleason closed 10 years ago

mgleason commented 10 years ago

I've noticed that when a modified record is saved via [record.managedObjectContext MR_saveToPersistentStoreAndWait], two NSManagedObjectContext's save - which causes the following to be called twice:

-(void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject    // specifically NSFetchedResultsChangeUpdate

Apparently it's called once for "DEFAULT" and again for "BACKGROUND SAVING (ROOT)". This causes a problem for me because I end up with overlapping animations due the two calls being fired in rapid succession.

Is there a way to avoid this?

FYI - below are the logs output from a single save. The "Update at: 0" entries are from the didChangeObject method. Note the two NSManagedObjectContext's - 0x8ad3f40 (DEFAULT) and 0x8ada3e0 (BACKGROUND SAVING (ROOT)):

2013-12-10 17:34:33.882 Fred[43450:70b] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8ad3f40) → Saving <NSManagedObjectContext (0x8ad3f40): *** DEFAULT ***> on *** MAIN THREAD ***
2013-12-10 17:34:33.883 Fred[43450:70b] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8ad3f40) → Save Parents? 1
2013-12-10 17:34:33.883 Fred[43450:70b] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8ad3f40) → Save Synchronously? 1
2013-12-10 17:34:33.883 Fred[43450:70b] Update at: 0
2013-12-10 17:34:33.886 Fred[43450:70b] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8ada3e0) → Saving <NSManagedObjectContext (0x8ada3e0): *** BACKGROUND SAVING (ROOT) ***> on *** MAIN THREAD ***
2013-12-10 17:34:33.887 Fred[43450:70b] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8ada3e0) → Save Parents? 1
2013-12-10 17:34:33.887 Fred[43450:70b] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8ada3e0) → Save Synchronously? 1
2013-12-10 17:34:33.914 Fred[43450:70b] __70-[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:]_block_invoke21(0x8ada3e0) → Finished saving: <NSManagedObjectContext (0x8ada3e0): *** BACKGROUND SAVING (ROOT) ***> on *** MAIN THREAD ***
2013-12-10 17:34:33.916 Fred[43450:70b] Update at: 0
tonyarnold commented 10 years ago

If you look closely, two different contexts are being saved — first the main context, and then the parent context of that main context which actually saves to disk (although I'm not sure why the "Background Saving" context is saving on the main thread — that shouldn't be happening).

You need to restrict which context you're monitoring for changes — usually you only want to observe changes to the "main" context, not the background saving context.