4

Part of Apples description of the MVC-pattern is: ”The controller updates the model.” I interpret this to simply mean: The controller calls methods on the model, causing its internal state to change.

But for a controller object to call a method on a model object, it needs a reference to the model object. If multiple controllers need to update a model object, we need multiple references to the model object – one for each controller.

I don’t want my controllers to reach out in to global space locating other objects. I want higher level application objects to wire up lower level domain objects.

I’m coming from other plattforms where we use IOC containers for this stuff.

Looking for best practices as how model objects gets passed around in a cocoa application.

A concrete example: If I add CoreData to the cocoa application project template in xCode, the managedObjectContext is instantiated in the app delegate. How do I pass this instance to, for instance, a view controller or a nested view controller?

I’m using Swift.

weenzeel
  • 797
  • 5
  • 17

1 Answers1

2

concrete example: If I add CoreData to the cocoa application project template in xCode, the managedObjectContext is instantiated in the app delegate. How do I pass this instance to, for instance, a view controller or a nested view controller?

So personally I find this an anti-pattern: stuffing 'global' data in the app delegate.

But, that is what is very common on iOS and as you have noticed, what the standard Xcode template does. Unfortunately.

To make this a bit more workable, what I usually do is make the managedObjectContext private to the app delegate. Then when another object, mostly a UIViewController, needs to access this context, I explicitly pass it to the UIViewController when I instantiate it.

And when that view controller needs to display a new view controller, like for example some detail view, I again pass the context to it.

Then at least there a clearer form of responsibility. And it makes testing simpler because view controllers simply need to be configured (or injected in IoC terms) instead of grabbing hard coded global objects.

I know this not a full answer to what you were asking but I thought this bit was the most interesting of your question.

Stefan Arentz
  • 34,311
  • 8
  • 67
  • 88