Friday, August 10, 2012

Rails MVC vs iOS MVC

If your primary experience with Model View Controller (MVC) has been via Ruby on Rails, and then you switch over to iOS (iPhone / iPad) programming, see that it also supports MVC and think, "Oh, cool, I already know that!"  Not so fast.

I am not expert at either of these technologies, but let me put it in the best terms I can.  In the Rails world, the controller is primarily associated with manipulating the model.  You have a Person object, you have a PersonController.  That PersonController has actions like index (show a list of Person objects), show (a single Person), edit/update, create/save, destroy and so on.  Things that you can do with that object.  Each action, in general, has a view.  To the point where the default behavior of an action called "foo" on the PersonController is to assume that there is a file called foo in the /views/person directory.

In iOS world, each controller handles a single view.  I'm still trying to get my head around it.  I keep thinking of the View as an entirely separate object that I instantiate and "connect" to the controller in some way, such that the controller's only real job is to take in some user input, manipulate some stuff, and then let the next view do its thing.

Not really.  In fact, the controller can go ahead and just instantiate a UIView object and start populating it.  There' a method called viewDidLoad, that gets called when the view is all loaded.  Fair enough.  Where is that method?  Is there a didLoad() method on UIView?  Nope!  It's on the controller.  So it's practically hard coded in the framework that a controller deals with "the view" and you don't get to trick it into managing many views.

I don't yet fully get it.

UPDATE - As I do more googling on stuff like "switch UIView" I'm learning some techniques for how to manage multiple views inside a controller.  It's not quite the same thing as having a specific view associated with a specific action like Rails does, but it's inaccurate to say that a controller can only handle a single view at a time. It's more like, "The controller has a pointer to a view.  You are free to swap out and/or otherwise regenerate that view according to whatever rules you like."  So I don't think I have to have a PeopleIndexController and a PeopleShowController and a PeopleEditController...

No comments: