objective-cmagicalrecordensembles

Ensembles: when to use MagicalRecord's saveWithCompletion vs saveAndWait


I have an existing app (uses MagicalRecord) that I am trying to incorporate Ensembles. I have come across several places in my app where I save using MR_saveToPersistentStoreWithCompletion. I noticed in the Ensembles MagicalRecord example that it uses MR_saveToPersistentStoreAndWait.

I know what the difference is between the two; the question is: with Ensembles, should I always use MR_saveToPersistentStoreAndWait? If not, what are the circumstances that I should use MR_saveToPersistentStoreWithCompletion?


Solution

  • The main thing to be aware is that using the completion block involves an asynchronous save in the background, and once that save completes, Ensembles has to capture the changes from the notification that is fired.

    In general, this is not a problem, but when terminating or going to the background, it is important to give Ensembles a chance to finish saving what it observes in the notification. You should thus use the save-and-wait variation in that case, to make sure the store is fully saved BEFORE you use the processPendingChanges... method on your ensemble. If you instead use the non-blocking method, you can't be sure the save is finished when you ask Ensembles to process pending changes, so there is a risk that it will not complete before the app is terminated.

    There is a more exotic complication with saving in the background that involves creating objects with the same global identifier on different devices, but it will only affect a small number of apps. You can read more about that case in the Ensembles book.