Just looking for a little feedback on if this is a bad idea for sharing the Managed Object Context.
In the MyApp-Prefix.pch file I have added following:
#import "AppDelegate.h"
#define MOC [(AppDelegate*)[UIApplication sharedApplication].delegate managedObjectContext]
Then when I need to access the context I do the following (just an example):
[MOC deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];
This seems to work great, but it also seems too easy, especially since I don’t see it mentioned anywhere. Is this a bad design pattern?
Thanks for any feedback
Instead of a compiler macro (which can cause surprises sometimes) I usually define a class method on my app delegate, like this:
Then, when I need a reference to some global state, I can call it like this:
If your app is complex enough, it might be worth the trouble of passing around a reference to a managed object context, rather than using a global one. If you do, it becomes easier to refactor and use other techniques later, like child contexts to group changes.
To be specific, that means each view controller has it’s own managedObjectContext instance variable. When you present a new view controller, you pass along a reference: maybe in a custom init method, maybe by setting a property. None of your classes (except maybe the root view controller) ever reference your global app delegate. This way, if you had a complicated editing view, you could give it a child context where it could save changes “temporarily” (to verify that all the objects are valid); if the user hits the cancel button, you just throw the whole context away.
Also, if you’re always using the global context, you might have bugs that are hard to track down. For example, an edit view that doesn’t clean up after itself leaves an invalid object behind. Then the next time you go to save something unrelated, you get an error! Happened to me, was no fun to debug.