iPhone MVC for Rail devs
There are a good number of Rails developers becoming interested in iPhone development recently. At first glance, it is hard to imagine what would cause a sane programmer to leave the expressive and enjoyable Ruby for some strange version of C with even more punctuation.
But after diving in to the code, you'll notice there are clearly some shared values. The Model/View/Controller pattern shows up often in the cocoa documentation and samples.
So what are the key differences between Rails & iPhone MVC?
One immediately apparent difference is that storing model, view, and controller classes in separate directories does not seem to be standard practice. XCode will allow you to organize your classes into "Groups", and some apps do utilize this to organize separate the three (see the LocateMe sample app), but you'll mostly be using the filename to determine if something is a view, controller or model. In some of the samples you'll just see all the code put into a view, which might be ok to illustrate a particular feature, but I wouldn't recommend for the maintainability of your code. This is the Cocoa equivalent of putting all your application logic in your ERB templates.
Views in Cocoa Touch are usually subclasses of the UIView class. You render into a view by implementing the drawRect method, or by adding other elements (subviews) into your view. Cocoa touch provides a nice set of UI elements, from the sophisticated UIWebView, which is essentially an embedded Safari widget, to simpler control elements like labels and switches. Very loosely, UIView superviews translate to html pages and subviews to partials.
The second member of the triumvirate, the controller, is played by UIViewController. Typically called 'view controllers', they separate the details of the models from the views, just like controllers in Rails. Each view controller is responsible for one 'page' or full screen of your application, so they're more granular than Rails controllers, which typically control many pages/actions. You can set up view controllers manually, or use Interface Builder, which lets you place and arrange GUI elements graphically. Actions (called 'outlets') from GUI elements are connected to methods the view controller, which then updates the appropriate models.
The place for all the core logic of your app is, of course, the model. Model objects can be objective C objects, or even plain old c++ objects, and are responsible for the actual work of the application, such as storing/retrieving data, making network requests, interfacing with other aspects of the iphone, such as core location, audio, or the accelerometer.
The ostensible goal of MVC is to make your code more reusable and adaptable to change, and I think it succeeds for the most part on both platforms. At the very least, it's a small amount of familiarity for the Rails coder new to iPhone development.



