Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Apple documentation that getting ManagedObjectContext from UIApplicationDelegate is bad?

Just curious why ManagedObjectContexts should be passed to UIViewControllers when they are created, rather than just grabbing them from a UIApplicationDelegate?

The docs say that this makes your applications more rigid, but I am failing to see the nuances of when to use which pattern.

Thanks!

like image 294
user798719 Avatar asked Jul 31 '11 04:07

user798719


2 Answers

Imagine that I ask you to do some task, like painting a room. If I just tell you "go paint a room," you'll need to ask me a lot of questions, like:

  • Which room?
  • Where's the paint?
  • Where are the brushes?
  • Should I use a dropcloth?

In short, you won't be able to complete the task without help from me. If you have to depend on me every time, you won't be a very flexible painter. One way to deal with that problem is for me to give you all the stuff you need at the outset. Instead of "go paint a room," I'll say "please paint room number 348 using this bucket of paint and this brush, and don't bother with a dropcloth." Now, you've got everything you need, and you can get right to work with no further help from me. You're a much more flexible worker because you no longer depend on me.

The same thing applies to view controllers (and objects generally); it's better to give them everything they need than to have them depend on a particular object like the app delegate. It's true not just for managed object contexts, but for any information they need to do their job.

like image 188
Caleb Avatar answered Sep 22 '22 17:09

Caleb


This is mainly because you want to use dependency injection with your UIViewControllers instead of just grabbing everything from UIApplication, this keeps your delegate clean instead of full of reference hacks.

This is also to keep with the MVC pattern:

  1. Model

  2. View Controller (Only for view logic)

  3. Controller (For coordinating between the view and the model)

like image 30
Oscar Gomez Avatar answered Sep 25 '22 17:09

Oscar Gomez