I am a newbie in iOS application development, but I am trying to learn how to deal with Cocoa in the best way.
I got stuck trying to understand how to keep and reference the model objects properly.
- many say to write an app delegate property to hold the model and then reference it through the convenience methods for the app delegate singleton.
- others say to “inject” in the view controller only the part of model which it needs (or its subviews needs), but I don’t understand how to do this. Via a property? Via an initWithModel: method (and in this case, how can I say to IB to use that method?)
- others again say that the model should be a singleton
- and again, others say to use global variables (!)
Could you please give me some hint (and code samples)? I would like to learn the things in the proper manner, considering that soon I will be moving towards Core Data.
Abstract: I read carefully the topic Where to place the "Core Data Stack" in a Cocoa/Cocoa Touch application suggested by Brad Larson and I wrote a possible solution on how to deal with a model and different view controllers. The solution doesn’t use Core Data, but I believe that the same design may be applied to Core Data apps.
Scenario: let’s consider a simple application which stores information about products, such as name, description and price/unit. Once launched, the application shows a list of products (with a UITableView); when the user taps on a product name, the application presents product details in another view, updating the navigation bar with the product name.
Architecture The model is pretty simple here: an array of Product objects, each one with a name, a description and a price property.
The application has got three main views, mostly created by the Navigation template of Xcode: a UINavigationView (managed by the UINavigationController, instantiated in the app delegate), the default UITableView (managed by RootViewController and which is the first view shown by the UINavigationController) and a DetailView (managed by the DetailViewController class we have to write).
Let’s see what’s the big plan from the model point of view:
Here some code snippets:
Creation of the model:
The RootViewController can receive the model reference, since it has a NSMutableArray property:
When the user taps on a product name, the RootViewController instantiates a new DetailViewController and passes the reference to the single product to it using a property again.
And, at the end, the DetailViewController shows the model information setting its outlets in the viewDidLoad method.
You can download the full project here: http://dl.dropbox.com/u/1232650/linked/stackoverflow/SimpleModel.zip
I will really appreciate any comment to my solution, I am eager to learn 😉