What are the Downsides to Putting the Core Data MOC in the App Delegate?

I saw this question on the iOSProgramming topic in reddit:

I’ve seen a number of different ways to access the NSManagedObjectContext when working with Core Data, but I was wondering if there are any downsides to the way I’ve been doing it. Basically, I stick a computed variable in the AppDelegate, and grab it when I need it…

Please let me know if you see any flaws… If not, feel free to use it!

The writer then shows the following code which is the computed variable:

There are a number of downsides to this:

  1. The app delegate is managing the Core Data stack. Classes should only have one responsibility. The app delegate is already responsible for managing application lifecycle. It shouldn’t be managing the Core Data stack as well.
  2. You are completely dependent on Core Data and using it as your persistence method for your app. What if you decide to switch to Realm or something?
  3. Any code you write that uses myManagedObjectContext will be dependent on the App Delegate.
  4. Any tests you write will be dependent on the App Delegate and Core Data and will be hard to test and slow as a result.

This is basically the lazy developer’s way of doing things. Granted the Xcode templates generate the Core Data code in the app delegate and doing this makes it easy to get the MOC, but Apple’s example code and the Xcode templates are not always the best way to do things. They are frequently the opposite.

In this post, let’s just focus on the 2nd issue, that of being dependent on Core Data and using it as your persistence method. Perhaps I will cover the other issues in future posts.

Continue reading →