SlideShare a Scribd company logo
1 of 27
Download to read offline
Model-View-Controller
Pattern
Model-View-Controller
Controller
View Model
User action Update
Update Notify
Controller
Model objects
Groups the data needed for a specific problem domain or a type of solution to be built

Can be related to other model objects
Model
Communication
Model objects
View Model
User action Update
Update Notify
Controller
Views
Displays data about the app’s model objects and allows user to edit the data

Can be reused to show different instances of the model data
View
Communication
Views
Controller
View Model
User action Update
Update Notify
Controller
Controllers
Acts as the messenger between views and model objects

Types:

• View controllers

• Model controllers

• Helper controllers
Model
Controllers
Helps control a model object or collection of model objects

Three common reasons to create a model controller:

• Multiple objects or scenes need access to the model data

• Logic for adding, modifying, or deleting model data is complex

• Keep the code in view controllers focused on managing the views

Crucial in larger projects for readability and maintainability
Helper
Controllers
Useful to consolidate related data or functionality so that it can be accessed by 

other objects in your app
Controller
Communication
Controllers
Controller
View Model
User action Update
Update Notify
Controller
Meal tracker example
Creating an app to track eaten meals

• What should be in a "Meal" model object?

• What views are needed to display meals? 

• How many controllers makes sense?
Model
Meal tracker example
Meal:

• Name

• Photo

• Notes

• Rating

Plus a timestamp
Model
Model
Meal tracker example
struct Meal {
var name: String
var photo: UIImage
var notes: String
var rating: Int
var timestamp: Date
}
Model
Views
Meal tracker example
Two possible views:

• List of all tracked meals

• Details of each meal

Each needs a view controller class
View
Controllers
Meal tracker example
Minimum of two controllers:

• List view

• Detail view
Controller
Meal list table view controller
Meal tracker example
class MealListTableViewController: UITableViewController {
var meals: [Meal] = []
@IBOutlet weak var tableView: UITableView!
}
Controller
Meal list table view controller
Meal tracker example
class MealListTableViewController: UITableViewController {
var meals: [Meal] = []
func saveMeals() {...}
func loadMeals() {...}
}
Controller
class MealListTableViewController: UITableViewController {
let meals: [Meal] = []
override func viewDidLoad() {
// load the meals and set up the table view
}
// Required table view methods
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {...}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {...}
// Navigation methods
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Pass the selected meal to the MealDetailViewController
}
@IBAction func unwindToMealList(sender: UIStoryboardSegue) {
// Capture the new or updated meal from the MealDetailViewController and save it to the meals
property
}
// Persistence methods
func saveMeals() {
// Save the meals model data to the disk
}
func loadMeals() {
// Load meals data from the disk and assign it to the meals property
}
}
Meal detail view controller
Meal tracker example
class MealDetailViewController: UIViewController {...}
class MealDetailViewController: UIViewController, UIImagePickerControllerDelegate {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var photoImageView: UIImageView!
@IBOutlet weak var ratingControl: RatingControl!
@IBOutlet weak var saveButton: UIBarButtonItem!
var meal: Meal?
override func viewDidLoad() {
if let meal = meal {
update(meal)
}
}
func update(_ meal: Meal) {
// Update all outlets to reflect the data about the meal
}
// Navigation methods
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Update the meal property that will be accessed by the MealListTableViewController to update the
list of meals
}
@IBAction func cancel(_ sender: UIBarButtonItem) {
// Dismiss the view without saving the meal
}
Reminder
Model-View-Controller is a useful pattern

More than one way to implement it

Everyone has their own style

Yours will evolve as you gain experience
Project organization
Use clear, descriptive filenames

Create separate files for each of your type
definitions

Write your code as if complete strangers are going
to read it

Group files to help organize your code
Model-View-Controller
Learn how to organize files, structures, and classes into a design pattern called
MVC, which stands for Model-View-Controller. 

MVC will help you architect the files in your app, as well as the interactions and
relationships between different types and instances.
Lab: Favorite Athletes
Plan out and create an app that uses proper MVC design. Your app will have two
screens for displaying the user’s favorite athletes. 

It will allow the user to add new athletes to the list, as well as to edit existing entries.
© 2017 Apple Inc. 

This work is licensed by Apple Inc. under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license.

More Related Content

Similar to Model View Controller

iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 04)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 04)iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 04)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 04)Jonathan Engelsma
 
Porting the Legacy Application to Composite Application Guidance
Porting the Legacy Application to Composite Application GuidancePorting the Legacy Application to Composite Application Guidance
Porting the Legacy Application to Composite Application GuidanceOur Community Exchange LLC
 
Ios development 2
Ios development 2Ios development 2
Ios development 2elnaqah
 
Introduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumarIntroduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumarAppfinz Technologies
 
Adding custom ui controls to your application (1)
Adding custom ui controls to your application (1)Adding custom ui controls to your application (1)
Adding custom ui controls to your application (1)Oro Inc.
 
LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLAkhil Mittal
 
How to instantiate any view controller for free
How to instantiate any view controller for freeHow to instantiate any view controller for free
How to instantiate any view controller for freeBenotCaron
 
Simple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanGigin Krishnan
 
Ctools presentation
Ctools presentationCtools presentation
Ctools presentationDigitaria
 
How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30fiyuer
 
App coordinators in iOS
App coordinators in iOSApp coordinators in iOS
App coordinators in iOSUptech
 
ASP.NET MVC Fundamental
ASP.NET MVC FundamentalASP.NET MVC Fundamental
ASP.NET MVC Fundamentalldcphuc
 

Similar to Model View Controller (20)

iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 04)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 04)iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 04)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 04)
 
Mvc architecture
Mvc architectureMvc architecture
Mvc architecture
 
WPF Line of Business Control Templates Styles
WPF Line of Business Control Templates StylesWPF Line of Business Control Templates Styles
WPF Line of Business Control Templates Styles
 
Model viewviewmodel2
Model viewviewmodel2Model viewviewmodel2
Model viewviewmodel2
 
Porting the Legacy Application to Composite Application Guidance
Porting the Legacy Application to Composite Application GuidancePorting the Legacy Application to Composite Application Guidance
Porting the Legacy Application to Composite Application Guidance
 
Ios development 2
Ios development 2Ios development 2
Ios development 2
 
Introduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumarIntroduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumar
 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
 
Adding custom ui controls to your application (1)
Adding custom ui controls to your application (1)Adding custom ui controls to your application (1)
Adding custom ui controls to your application (1)
 
CodeIgniter 101 Tutorial
CodeIgniter 101 TutorialCodeIgniter 101 Tutorial
CodeIgniter 101 Tutorial
 
CH08.ppt
CH08.pptCH08.ppt
CH08.ppt
 
CH08.ppt
CH08.pptCH08.ppt
CH08.ppt
 
LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQL
 
How to instantiate any view controller for free
How to instantiate any view controller for freeHow to instantiate any view controller for free
How to instantiate any view controller for free
 
Simple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnan
 
Form part1
Form part1Form part1
Form part1
 
Ctools presentation
Ctools presentationCtools presentation
Ctools presentation
 
How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30
 
App coordinators in iOS
App coordinators in iOSApp coordinators in iOS
App coordinators in iOS
 
ASP.NET MVC Fundamental
ASP.NET MVC FundamentalASP.NET MVC Fundamental
ASP.NET MVC Fundamental
 

More from SV.CO

Handout level-1-module-1
Handout   level-1-module-1Handout   level-1-module-1
Handout level-1-module-1SV.CO
 
Persistence And Documents
Persistence And DocumentsPersistence And Documents
Persistence And DocumentsSV.CO
 
Building complex input screens
Building complex input screensBuilding complex input screens
Building complex input screensSV.CO
 
Working with the Web: 
Decoding JSON
Working with the Web: 
Decoding JSONWorking with the Web: 
Decoding JSON
Working with the Web: 
Decoding JSONSV.CO
 
Saving Data
Saving DataSaving Data
Saving DataSV.CO
 
Alerts notification
Alerts notificationAlerts notification
Alerts notificationSV.CO
 
UI Dynamics
UI DynamicsUI Dynamics
UI DynamicsSV.CO
 
Practical animation
Practical animationPractical animation
Practical animationSV.CO
 
Segues and navigation controllers
Segues and navigation controllersSegues and navigation controllers
Segues and navigation controllersSV.CO
 
Camera And Email
Camera And EmailCamera And Email
Camera And EmailSV.CO
 
Scroll views
Scroll viewsScroll views
Scroll viewsSV.CO
 
Intermediate table views
Intermediate table viewsIntermediate table views
Intermediate table viewsSV.CO
 
Table views
Table viewsTable views
Table viewsSV.CO
 
Closures
ClosuresClosures
ClosuresSV.CO
 
Protocols
ProtocolsProtocols
ProtocolsSV.CO
 
App anatomy and life cycle
App anatomy and life cycleApp anatomy and life cycle
App anatomy and life cycleSV.CO
 
Extensions
ExtensionsExtensions
ExtensionsSV.CO
 
Gestures
GesturesGestures
GesturesSV.CO
 
View controller life cycle
View controller life cycleView controller life cycle
View controller life cycleSV.CO
 
Controls in action
Controls in actionControls in action
Controls in actionSV.CO
 

More from SV.CO (20)

Handout level-1-module-1
Handout   level-1-module-1Handout   level-1-module-1
Handout level-1-module-1
 
Persistence And Documents
Persistence And DocumentsPersistence And Documents
Persistence And Documents
 
Building complex input screens
Building complex input screensBuilding complex input screens
Building complex input screens
 
Working with the Web: 
Decoding JSON
Working with the Web: 
Decoding JSONWorking with the Web: 
Decoding JSON
Working with the Web: 
Decoding JSON
 
Saving Data
Saving DataSaving Data
Saving Data
 
Alerts notification
Alerts notificationAlerts notification
Alerts notification
 
UI Dynamics
UI DynamicsUI Dynamics
UI Dynamics
 
Practical animation
Practical animationPractical animation
Practical animation
 
Segues and navigation controllers
Segues and navigation controllersSegues and navigation controllers
Segues and navigation controllers
 
Camera And Email
Camera And EmailCamera And Email
Camera And Email
 
Scroll views
Scroll viewsScroll views
Scroll views
 
Intermediate table views
Intermediate table viewsIntermediate table views
Intermediate table views
 
Table views
Table viewsTable views
Table views
 
Closures
ClosuresClosures
Closures
 
Protocols
ProtocolsProtocols
Protocols
 
App anatomy and life cycle
App anatomy and life cycleApp anatomy and life cycle
App anatomy and life cycle
 
Extensions
ExtensionsExtensions
Extensions
 
Gestures
GesturesGestures
Gestures
 
View controller life cycle
View controller life cycleView controller life cycle
View controller life cycle
 
Controls in action
Controls in actionControls in action
Controls in action
 

Recently uploaded

Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 

Recently uploaded (20)

Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 

Model View Controller

  • 3. Model objects Groups the data needed for a specific problem domain or a type of solution to be built Can be related to other model objects Model
  • 4. Communication Model objects View Model User action Update Update Notify Controller
  • 5. Views Displays data about the app’s model objects and allows user to edit the data Can be reused to show different instances of the model data View
  • 7. Controllers Acts as the messenger between views and model objects Types: • View controllers • Model controllers • Helper controllers
  • 8. Model Controllers Helps control a model object or collection of model objects Three common reasons to create a model controller: • Multiple objects or scenes need access to the model data • Logic for adding, modifying, or deleting model data is complex • Keep the code in view controllers focused on managing the views Crucial in larger projects for readability and maintainability
  • 9. Helper Controllers Useful to consolidate related data or functionality so that it can be accessed by 
 other objects in your app Controller
  • 11. Meal tracker example Creating an app to track eaten meals • What should be in a "Meal" model object? • What views are needed to display meals? • How many controllers makes sense?
  • 12. Model Meal tracker example Meal: • Name • Photo • Notes • Rating Plus a timestamp Model
  • 13. Model Meal tracker example struct Meal { var name: String var photo: UIImage var notes: String var rating: Int var timestamp: Date } Model
  • 14. Views Meal tracker example Two possible views: • List of all tracked meals • Details of each meal Each needs a view controller class View
  • 15. Controllers Meal tracker example Minimum of two controllers: • List view • Detail view Controller
  • 16. Meal list table view controller Meal tracker example class MealListTableViewController: UITableViewController { var meals: [Meal] = [] @IBOutlet weak var tableView: UITableView! } Controller
  • 17. Meal list table view controller Meal tracker example class MealListTableViewController: UITableViewController { var meals: [Meal] = [] func saveMeals() {...} func loadMeals() {...} } Controller
  • 18. class MealListTableViewController: UITableViewController { let meals: [Meal] = [] override func viewDidLoad() { // load the meals and set up the table view } // Required table view methods override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {...} override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {...}
  • 19. // Navigation methods override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Pass the selected meal to the MealDetailViewController } @IBAction func unwindToMealList(sender: UIStoryboardSegue) { // Capture the new or updated meal from the MealDetailViewController and save it to the meals property } // Persistence methods func saveMeals() { // Save the meals model data to the disk } func loadMeals() { // Load meals data from the disk and assign it to the meals property } }
  • 20. Meal detail view controller Meal tracker example class MealDetailViewController: UIViewController {...}
  • 21. class MealDetailViewController: UIViewController, UIImagePickerControllerDelegate { @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var photoImageView: UIImageView! @IBOutlet weak var ratingControl: RatingControl! @IBOutlet weak var saveButton: UIBarButtonItem! var meal: Meal? override func viewDidLoad() { if let meal = meal { update(meal) } } func update(_ meal: Meal) { // Update all outlets to reflect the data about the meal }
  • 22. // Navigation methods override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Update the meal property that will be accessed by the MealListTableViewController to update the list of meals } @IBAction func cancel(_ sender: UIBarButtonItem) { // Dismiss the view without saving the meal }
  • 23. Reminder Model-View-Controller is a useful pattern More than one way to implement it Everyone has their own style Yours will evolve as you gain experience
  • 24. Project organization Use clear, descriptive filenames Create separate files for each of your type definitions Write your code as if complete strangers are going to read it Group files to help organize your code
  • 25. Model-View-Controller Learn how to organize files, structures, and classes into a design pattern called MVC, which stands for Model-View-Controller. MVC will help you architect the files in your app, as well as the interactions and relationships between different types and instances.
  • 26. Lab: Favorite Athletes Plan out and create an app that uses proper MVC design. Your app will have two screens for displaying the user’s favorite athletes. It will allow the user to add new athletes to the list, as well as to edit existing entries.
  • 27. © 2017 Apple Inc. This work is licensed by Apple Inc. under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license.