SlideShare ist ein Scribd-Unternehmen logo
1 von 27
Downloaden Sie, um offline zu lesen
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.

Weitere ähnliche Inhalte

Ähnlich wie Model View Controller

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
LearningMVCWithLINQToSQL
Akhil Mittal
 
Ctools presentation
Ctools presentationCtools presentation
Ctools presentation
Digitaria
 
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
fiyuer
 
ASP.NET MVC Fundamental
ASP.NET MVC FundamentalASP.NET MVC Fundamental
ASP.NET MVC Fundamental
ldcphuc
 

Ähnlich wie 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
 

Mehr von 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
 

Kürzlich hochgeladen

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Kürzlich hochgeladen (20)

On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 

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.