I’m working on an iPhone application and trying to conform to MVC as much as possible (I’m still learning). I have an Unsigned integer in my data model that represents a number of seconds. I want this to be displayed in a view in the format ’00:00′(minutes:seconds). My question is, where should this formatting take place?
Is it the model object’s responsibility to be able to provide it in this format?
Does the controller format this after taking it from the model but before passing it to the view?
Or does the view handle the formatting?
Thank you for any help.
If this formatting is only used in one place, the best solution is to put formatting into the view, and this approach often works quite well. If you do not have a custom view, however, then it is natural to put this work into the view controller. In Cocoa’s version of MVC, view controllers are allowed broad flexibility in how they manage the views. (This is a significant place that Cocoa’s MVC differs from SmallTalk’s MVC, which it is based on.)
But what if you want to share the same formatting between views (or view controllers)? Then you factor out the formatting code into an
NSFormattersubclass (or use an existingNSDateFormatterin your case). You can pass these around, put then in ivars, or even create a Singleton to hold them.Why not just put it in the model in that case? Well, say you have four views that show the time this way, but you then add two other views that shows the time as 00:00.0, and then there’s one accumulator view that shows hours and minutes. Now you have to keep expanding the model to handle these cases. The model is picking up more and more information about the views. Keeping the formatting in a formatter allows you to share the code (and bug fixes) without polluting the model with these details. And views that have very special formatting needs can still have their own custom code.
There’s no need to create separate
NSFormattersubclasses for every kind of formatting. You can create a singleMYObjectFormatterclass that takes options like “hours,” “minutes,” “seconds,” etc. It would work just like anNSDateFormatterin this regard, and give the simplicity of use you need, while keeping your formatting code out of the model. This is exactly howNSDateandNSDateFormatterare partitioned.