SlideShare a Scribd company logo
Using a Model-View-ViewModel
architecture for iOS Apps
Allan Shih
Agenda
● Problems of MVC
● Introduction to Model-View-ViewModel (MVVM)
○ Model
○ View
○ Controller
○ View Model
○ Data Manager
● Implementation
● Reference
Model-View-Controller
● A proven pattern for organizing code in complex
application design
● Separates an application into three main logical
components: model, view, and controller
Realistic Cocoa MVC
● Cocoa MVC encourages you to write Massive View Controllers,
because they are so involved in View’s life cycle that it’s hard to
say they are separate.
Problems of MVC
● MVC frameworks tend to lead to Apps with
Massive View Controllers
● Network calls, persistence, view logic, and all
other sorts of code ends up in the Controller.
● This Makes Controller code
○ difficult to read
○ difficult to change
○ difficult to unit test
○ difficult to reuse
Model-View-ViewModel (MVVM)
● The MVVM treats the view controller as the View
● There is no tight coupling between the View and
the Model
Model
● The same responsibility as in MVC
● Used to represent a “model” of some set of data
● For example: a model of a date, event, or place
● This typically involves having an NSObject class file
with properties
○ Hold data about the model object
○ Possibly some business logic around that model object.
View
● Used to represent the user interface (UI) of the app
● This can include UIViews, UIButtons, UITableViewCells,
UICollectionViewCells and UIViews on a storyboard
● A view shouldn’t directly interact with data model objects
○ It should instead have a function that takes in a set of parameters
representing data
Controller
● Used to set up the UI of views and handle any user
interaction with these views
● Like views, the controller shouldn’t directly interact with
the data model objects
○ It should ask its view model to set up a view with data instead.
○ Any state and business logic of the view controller will be kept by its
view model
View model
● Used to represent a model of a view controller
● All state and business logic associated with a view
controller will be kept by its view model
● A view model will trigger all calls to send and receive
data (using data managers)
● The view model doesn’t know about the view controller
Data manager
● Used to make and handle all calls to get data
● JSON parsing and serialization of this data to data
model objects
● Cache data
● Hold any state related to the data
● A view model will trigger the data manager to make and
handle data calls
Implementation
Data manager
class DataManager {
static let sharedInstance: DataManager = DataManager()
func getData(callback : ((result : [DataObject])->()){
//code to get data i.e. some rest call
//parse JSON and serialize to an array of data model objects
//return array of data model objects by calling the callback
parameter
callback(result: result)
}
}
View Model - Init
class ViewModel {
var reloadCollectionViewCallback : (()->())!
var dataArray = [DataObject]()
init(reloadCollectionViewCallback : (()->()) {
self.reloadCollectionViewCallback = reloadCollectionViewCallback
retrieveData()
}
...
}
View Model - Retrieve Data
class ViewModel {
var reloadCollectionViewCallback : (()->())!
var dataArray = [DataObject]()
...
func retrieveData(){
DataManager.SharedInstance.getData({ result in
self.dataArray = result
self.reloadCollectionViewCallback()
}
}
}
View Controller - Init View Model
class ViewController: UIViewController {
var viewModel : ViewModel!
override func viewDidLoad(){
super.viewDidLoad()
setupCollectionView()
viewModel = ViewModel(reloadCollectionViewCallback :
reloadCollectionViewData)
}
}
View Controller - Setup and Reload Collection View
class ViewController: UIViewController {
...
func setupColllectionView() {
collectionView.delegate = self
collectionView.dataSource = self
}
func reloadCollectionViewData() {
collectionView.reloadData()
}
}
View Controller - UICollectionViewDataSource
extension ViewController: UICollectionViewDataSource {
func numberOfSectionsInCollectionView(collectionView:
UICollectionView) -> Int {
return viewModel.numberOfSectionsInCollectionView()
}
func collectionView(collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return viewModel.numberOfItemsInSection(section)
}
}
View Controller - Setup Collection View Cell
extension ViewController: UICollectionViewDataSource {
...
func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) ->
UICollectionViewCell {
return viewModel.setUpCollectionViewCell(indexPath,
collectionView : collectionView)
}
}
View Model - Number of Items in Sections
// class ViewModel {
var dataArray : [DataObject]!
let kNumberOfSectionsInCollectionView = 1
func numberOfItemsInSection(section : Int) -> Int {
return dataArray.count
}
func numberOfSectionsInCollectionView() -> Int {
return kNumberOfSectionsInCollectionView
}
//}
View Model - Set up the collection view cell
// class ViewModel {
func setUpCollectionViewCell(indexPath : NSIndexPath, collectionView :
UICollectionView) -> UICollectionViewCell {
let dataObject = dataArray[indexPath.row]
let cell =
collectionView.dequeueReusableCellWithReuseIdentifier(“cell”,
forIndexPath: indexPath) as! MyCollectionViewCell
cell.setupData(name: dataObject.name, address: dataObject.address)
return cell
}
View - Collection view cell
class MyCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var addressLabel: UILabel!
func setupData(name : String?, address: String?){
nameLabel.text = name ?? “”
addressLabel.text = address ?? “”
}
}
ViewController - Keep track of the index path of the selected cell
extension ViewController: UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView,
didSelectItemAtIndexPath indexPath: NSIndexPath) {
viewModel.setSelectedCellIndexPath(indexPath)
performSegue(WithIdentifier: “toNextViewController”, sender:
self)
}
}
ViewController - Segue to a new view controller
//class ViewController: UIViewController {
override func prepareForSegue(segue: UIStoryboardSegue, sender:
AnyObject?) {
if segue.identifier == “toNextViewController” {
let nextVC = segue.destinationViewController as!
NextViewController
nextVC.viewModel =
viewModel.getNextViewControllerViewModel()
}
}
//}
View Model - The index path of the selected cell
//class ViewModel : NSObject {
var selectedCellIndexPath : NSIndexPath!
...
func setSelectedCellIndexPath(indexPath : NSIndexPath) {
selectedCellIndexPath = indexPath
}
//}
View Model - Initialize the next view controller’s view model
//class ViewModel : NSObject {
func getNextViewControllerViewModel() ->
NextViewControllerViewModel {
let dataObject = dataArray[selectedCellIndexPath]
let nextViewControllerViewModel =
NextViewControllerViewModel(dataObject: dataObject)
return nextViewControllerViewModel
}
//}
Summery
● The view controller should only be responsible for
displaying UI and handling user interaction.
● Business logic, state, and data handling should be taken
out of the view controller and put into the view controller’s
view model.
● Only view models and data managers are allowed to
directly touch data model objects
○ view controllers and views should not.
Demo
Reference
● The Swift Programming Language (Swift 3.0.1)
● Swift and Model-View-ViewModel in Practice
● Swift Tutorial: An Introduction to the MVVM Design Pattern
● MVVM in Swift

More Related Content

PDF
iOS architecture patterns
PDF
Model-View-Controller: Tips&Tricks
PPTX
Mvvm basics
PPT
Why MVC?
PPT
MVC Architecture in ASP.Net By Nyros Developer
PPTX
GUI patterns : My understanding
PPTX
MVVM Lights
PPTX
Knockout implementing mvvm in java script with knockout
iOS architecture patterns
Model-View-Controller: Tips&Tricks
Mvvm basics
Why MVC?
MVC Architecture in ASP.Net By Nyros Developer
GUI patterns : My understanding
MVVM Lights
Knockout implementing mvvm in java script with knockout

What's hot (20)

PDF
MVVM Light Toolkit Works Great, Less Complicated
PPT
Introduction to ASP.NET MVC
PPTX
Mortal Kombat! ASP.NET MVC vs ASP.NET Webforms – ASP.NET MVC is amazing
PPTX
Sexy Architecting. VIPER: MVP on steroids
PPTX
ASP .Net MVC 5
PDF
[@NaukriEngineering] MVVM in iOS
PDF
MV(C, mvvm) in iOS and ReactiveCocoa
PPTX
Angular js anupama
PDF
Introduction of angular js
PDF
ASP.NET MVC 3
PDF
Itroducing Angular JS
PDF
From mvc to viper
PPTX
Angular JS Indtrodution
PPTX
KnockOutjs from Scratch
PPTX
What's new in asp.net mvc 4
PPTX
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
PPTX
Introduction to WPF and MVVM
PPTX
Asp.net MVC training session
PPTX
Angular js presentation at Datacom
PDF
Break the monolith with (B)VIPER Modules
MVVM Light Toolkit Works Great, Less Complicated
Introduction to ASP.NET MVC
Mortal Kombat! ASP.NET MVC vs ASP.NET Webforms – ASP.NET MVC is amazing
Sexy Architecting. VIPER: MVP on steroids
ASP .Net MVC 5
[@NaukriEngineering] MVVM in iOS
MV(C, mvvm) in iOS and ReactiveCocoa
Angular js anupama
Introduction of angular js
ASP.NET MVC 3
Itroducing Angular JS
From mvc to viper
Angular JS Indtrodution
KnockOutjs from Scratch
What's new in asp.net mvc 4
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
Introduction to WPF and MVVM
Asp.net MVC training session
Angular js presentation at Datacom
Break the monolith with (B)VIPER Modules
Ad

Similar to Using a model view-view model architecture for iOS apps (20)

PPTX
Sitecore MVC (London User Group, April 29th 2014)
PPTX
Sitecore MVC (User Group Conference, May 23rd 2014)
PPT
ASP .net MVC
PDF
Optimize CollectionView Scrolling
PDF
MVVM & Data Binding Library
PDF
Backbone.js
PPTX
Swift Tableview iOS App Development
PDF
Say bye to Fragments with Conductor & Kotlin
PPTX
MVC.pptx
PPTX
Asp.Net Mvc
PPTX
ASP.NET MVC Controllers & Actions
PPTX
Spring Web MVC
PPTX
Controllers & actions
PPTX
Developing ASP.NET Applications Using the Model View Controller Pattern
PPTX
AngularJS.part1
PPTX
Chapter4.pptx
PPTX
MV* presentation frameworks in Javascript: en garde, pret, allez!
PDF
MVC architecture
PDF
Встреча №9. Будущее паттерна MVVM в iOS приложениях, Денис Лебедев
PDF
MVVM with Databinding and Google's new ViewModel. UA Mobile 2017.
Sitecore MVC (London User Group, April 29th 2014)
Sitecore MVC (User Group Conference, May 23rd 2014)
ASP .net MVC
Optimize CollectionView Scrolling
MVVM & Data Binding Library
Backbone.js
Swift Tableview iOS App Development
Say bye to Fragments with Conductor & Kotlin
MVC.pptx
Asp.Net Mvc
ASP.NET MVC Controllers & Actions
Spring Web MVC
Controllers & actions
Developing ASP.NET Applications Using the Model View Controller Pattern
AngularJS.part1
Chapter4.pptx
MV* presentation frameworks in Javascript: en garde, pret, allez!
MVC architecture
Встреча №9. Будущее паттерна MVVM в iOS приложениях, Денис Лебедев
MVVM with Databinding and Google's new ViewModel. UA Mobile 2017.
Ad

More from allanh0526 (17)

PPTX
PPTX
Digital authentication
PDF
Integration of slather and jenkins
PDF
How to generate code coverage reports in xcode with slather
PDF
Unit testing in xcode 8 with swift
PDF
Ui testing in xcode
PDF
How to work with dates and times in swift 3
PDF
ThingMaker in Swift
PDF
Automatic reference counting in Swift
PDF
Core data in Swfit
PDF
From android/java to swift (3)
PDF
From android/ java to swift (2)
PDF
From android/java to swift (1)
PDF
WebRTC
PDF
Pipeline interface
PDF
Deploying artifacts to archiva
PPT
Android httpclient
Digital authentication
Integration of slather and jenkins
How to generate code coverage reports in xcode with slather
Unit testing in xcode 8 with swift
Ui testing in xcode
How to work with dates and times in swift 3
ThingMaker in Swift
Automatic reference counting in Swift
Core data in Swfit
From android/java to swift (3)
From android/ java to swift (2)
From android/java to swift (1)
WebRTC
Pipeline interface
Deploying artifacts to archiva
Android httpclient

Recently uploaded (20)

PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Big Data Technologies - Introduction.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPT
Teaching material agriculture food technology
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
A Presentation on Artificial Intelligence
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Encapsulation theory and applications.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
cuic standard and advanced reporting.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Big Data Technologies - Introduction.pptx
Network Security Unit 5.pdf for BCA BBA.
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Teaching material agriculture food technology
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Review of recent advances in non-invasive hemoglobin estimation
A Presentation on Artificial Intelligence
NewMind AI Weekly Chronicles - August'25-Week II
Encapsulation theory and applications.pdf
Spectral efficient network and resource selection model in 5G networks
Unlocking AI with Model Context Protocol (MCP)
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Advanced methodologies resolving dimensionality complications for autism neur...
cuic standard and advanced reporting.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
20250228 LYD VKU AI Blended-Learning.pptx

Using a model view-view model architecture for iOS apps

  • 2. Agenda ● Problems of MVC ● Introduction to Model-View-ViewModel (MVVM) ○ Model ○ View ○ Controller ○ View Model ○ Data Manager ● Implementation ● Reference
  • 3. Model-View-Controller ● A proven pattern for organizing code in complex application design ● Separates an application into three main logical components: model, view, and controller
  • 4. Realistic Cocoa MVC ● Cocoa MVC encourages you to write Massive View Controllers, because they are so involved in View’s life cycle that it’s hard to say they are separate.
  • 5. Problems of MVC ● MVC frameworks tend to lead to Apps with Massive View Controllers ● Network calls, persistence, view logic, and all other sorts of code ends up in the Controller. ● This Makes Controller code ○ difficult to read ○ difficult to change ○ difficult to unit test ○ difficult to reuse
  • 6. Model-View-ViewModel (MVVM) ● The MVVM treats the view controller as the View ● There is no tight coupling between the View and the Model
  • 7. Model ● The same responsibility as in MVC ● Used to represent a “model” of some set of data ● For example: a model of a date, event, or place ● This typically involves having an NSObject class file with properties ○ Hold data about the model object ○ Possibly some business logic around that model object.
  • 8. View ● Used to represent the user interface (UI) of the app ● This can include UIViews, UIButtons, UITableViewCells, UICollectionViewCells and UIViews on a storyboard ● A view shouldn’t directly interact with data model objects ○ It should instead have a function that takes in a set of parameters representing data
  • 9. Controller ● Used to set up the UI of views and handle any user interaction with these views ● Like views, the controller shouldn’t directly interact with the data model objects ○ It should ask its view model to set up a view with data instead. ○ Any state and business logic of the view controller will be kept by its view model
  • 10. View model ● Used to represent a model of a view controller ● All state and business logic associated with a view controller will be kept by its view model ● A view model will trigger all calls to send and receive data (using data managers) ● The view model doesn’t know about the view controller
  • 11. Data manager ● Used to make and handle all calls to get data ● JSON parsing and serialization of this data to data model objects ● Cache data ● Hold any state related to the data ● A view model will trigger the data manager to make and handle data calls
  • 13. Data manager class DataManager { static let sharedInstance: DataManager = DataManager() func getData(callback : ((result : [DataObject])->()){ //code to get data i.e. some rest call //parse JSON and serialize to an array of data model objects //return array of data model objects by calling the callback parameter callback(result: result) } }
  • 14. View Model - Init class ViewModel { var reloadCollectionViewCallback : (()->())! var dataArray = [DataObject]() init(reloadCollectionViewCallback : (()->()) { self.reloadCollectionViewCallback = reloadCollectionViewCallback retrieveData() } ... }
  • 15. View Model - Retrieve Data class ViewModel { var reloadCollectionViewCallback : (()->())! var dataArray = [DataObject]() ... func retrieveData(){ DataManager.SharedInstance.getData({ result in self.dataArray = result self.reloadCollectionViewCallback() } } }
  • 16. View Controller - Init View Model class ViewController: UIViewController { var viewModel : ViewModel! override func viewDidLoad(){ super.viewDidLoad() setupCollectionView() viewModel = ViewModel(reloadCollectionViewCallback : reloadCollectionViewData) } }
  • 17. View Controller - Setup and Reload Collection View class ViewController: UIViewController { ... func setupColllectionView() { collectionView.delegate = self collectionView.dataSource = self } func reloadCollectionViewData() { collectionView.reloadData() } }
  • 18. View Controller - UICollectionViewDataSource extension ViewController: UICollectionViewDataSource { func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return viewModel.numberOfSectionsInCollectionView() } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return viewModel.numberOfItemsInSection(section) } }
  • 19. View Controller - Setup Collection View Cell extension ViewController: UICollectionViewDataSource { ... func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { return viewModel.setUpCollectionViewCell(indexPath, collectionView : collectionView) } }
  • 20. View Model - Number of Items in Sections // class ViewModel { var dataArray : [DataObject]! let kNumberOfSectionsInCollectionView = 1 func numberOfItemsInSection(section : Int) -> Int { return dataArray.count } func numberOfSectionsInCollectionView() -> Int { return kNumberOfSectionsInCollectionView } //}
  • 21. View Model - Set up the collection view cell // class ViewModel { func setUpCollectionViewCell(indexPath : NSIndexPath, collectionView : UICollectionView) -> UICollectionViewCell { let dataObject = dataArray[indexPath.row] let cell = collectionView.dequeueReusableCellWithReuseIdentifier(“cell”, forIndexPath: indexPath) as! MyCollectionViewCell cell.setupData(name: dataObject.name, address: dataObject.address) return cell }
  • 22. View - Collection view cell class MyCollectionViewCell: UICollectionViewCell { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var addressLabel: UILabel! func setupData(name : String?, address: String?){ nameLabel.text = name ?? “” addressLabel.text = address ?? “” } }
  • 23. ViewController - Keep track of the index path of the selected cell extension ViewController: UICollectionViewDelegate { func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { viewModel.setSelectedCellIndexPath(indexPath) performSegue(WithIdentifier: “toNextViewController”, sender: self) } }
  • 24. ViewController - Segue to a new view controller //class ViewController: UIViewController { override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == “toNextViewController” { let nextVC = segue.destinationViewController as! NextViewController nextVC.viewModel = viewModel.getNextViewControllerViewModel() } } //}
  • 25. View Model - The index path of the selected cell //class ViewModel : NSObject { var selectedCellIndexPath : NSIndexPath! ... func setSelectedCellIndexPath(indexPath : NSIndexPath) { selectedCellIndexPath = indexPath } //}
  • 26. View Model - Initialize the next view controller’s view model //class ViewModel : NSObject { func getNextViewControllerViewModel() -> NextViewControllerViewModel { let dataObject = dataArray[selectedCellIndexPath] let nextViewControllerViewModel = NextViewControllerViewModel(dataObject: dataObject) return nextViewControllerViewModel } //}
  • 27. Summery ● The view controller should only be responsible for displaying UI and handling user interaction. ● Business logic, state, and data handling should be taken out of the view controller and put into the view controller’s view model. ● Only view models and data managers are allowed to directly touch data model objects ○ view controllers and views should not.
  • 28. Demo
  • 29. Reference ● The Swift Programming Language (Swift 3.0.1) ● Swift and Model-View-ViewModel in Practice ● Swift Tutorial: An Introduction to the MVVM Design Pattern ● MVVM in Swift