Fundamental Design Pattern: ModelViewController
Cracking the ModelViewController Design Pattern
Design Patterns that will be covered in this article:
The MVC pattern simply is broken down into 3 main parts:
- Model — Models hold onto application data (typically in the form of structs or simple classes)
- View — Views communicate to their controller via IBActions
- View Controller — Controllers coordinate between models and views
Important to Note
- Models and views should not hold strong references to their owning controller because this would cause a retain cycle
- Use the MVC design pattern as a starting point and be open to implementing other patterns as you build your app
- When implementing a MVC design pattern, it’s convenient to organize your app bundle’s files with a Model, View, and Controller directory.
- I created a simple struct that represents a single programmer
- I created an IBOutlet for each of the properties I have in the Programmer model
- I set the class of the default UIView element to the view I set-up programmatically (ProgrammerView).
- I dragged 3 UITextFields from our Object Library and placed it within the UIView.
- Go ahead and connect the 3 UITextFields with the IBOutlets using the Connection Inspector of the UIView.
- Make sure to set Auto Layout constraints for your UI elements.
- In your main view controller, you can hold a strong reference to the view and model that it owns.
- It’s the controller’s job to coordinate between the model and view → In this case, the controller should update its view using the values from the model.
- If a programmer is set after viewDidLoad() is called, the controller should update ProgrammerView → You can use a didSet to accomplish this.
- This is an example of how the model can tell the controller that something has changed and that the view needs updating.
- Conversely, this is an example of how the view can tell the controller that something has changed and the model needs updating.
- I connected the IBAction to all three of the textfields in Main.storyboard.
- To see the IBAction work with a UITextField, I connected each of the textfields to the same IBAction with an Editing Changed event.
1. Not every object fits into a category of a model, view, or controller
2. Be-ware of the “Massive-View-Controller” or view controllers growing too big
3. Feel free to use other design patterns to build on top of MVC
In case if you haven’t yet, join my Discord server! I’m looking to create a community of developers so we can reinforce, motivate, and get to know each other in our programming journey.
If you have any questions or comments, please don’t feel afraid to ask or connect with me on social media! You can also send me an email at firstname.lastname@example.org