SlideShare a Scribd company logo
1 of 29
Download to read offline
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

What's hot

MVVM Light Toolkit Works Great, Less Complicated
MVVM Light ToolkitWorks Great, Less ComplicatedMVVM Light ToolkitWorks Great, Less Complicated
MVVM Light Toolkit Works Great, Less Complicatedmdc11
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVCSunpawet Somsin
 
Mortal Kombat! ASP.NET MVC vs ASP.NET Webforms – ASP.NET MVC is amazing
Mortal Kombat! ASP.NET MVC vs ASP.NET Webforms – ASP.NET MVC is amazingMortal Kombat! ASP.NET MVC vs ASP.NET Webforms – ASP.NET MVC is amazing
Mortal Kombat! ASP.NET MVC vs ASP.NET Webforms – ASP.NET MVC is amazingTom Walker
 
Sexy Architecting. VIPER: MVP on steroids
Sexy Architecting. VIPER: MVP on steroidsSexy Architecting. VIPER: MVP on steroids
Sexy Architecting. VIPER: MVP on steroidsDmytro Zaitsev
 
[@NaukriEngineering] MVVM in iOS
[@NaukriEngineering] MVVM in iOS[@NaukriEngineering] MVVM in iOS
[@NaukriEngineering] MVVM in iOSNaukri.com
 
MV(C, mvvm) in iOS and ReactiveCocoa
MV(C, mvvm) in iOS and ReactiveCocoaMV(C, mvvm) in iOS and ReactiveCocoa
MV(C, mvvm) in iOS and ReactiveCocoaYi-Shou Chen
 
Introduction of angular js
Introduction of angular jsIntroduction of angular js
Introduction of angular jsTamer Solieman
 
Angular JS Indtrodution
Angular JS IndtrodutionAngular JS Indtrodution
Angular JS Indtrodutionadesh21
 
KnockOutjs from Scratch
KnockOutjs from ScratchKnockOutjs from Scratch
KnockOutjs from ScratchUdaya Kumar
 
What's new in asp.net mvc 4
What's new in asp.net mvc 4What's new in asp.net mvc 4
What's new in asp.net mvc 4Simone Chiaretta
 
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...SoftServe
 
Introduction to WPF and MVVM
Introduction to WPF and MVVMIntroduction to WPF and MVVM
Introduction to WPF and MVVMSirar Salih
 
Asp.net MVC training session
Asp.net MVC training sessionAsp.net MVC training session
Asp.net MVC training sessionHrichi Mohamed
 
Angular js presentation at Datacom
Angular js presentation at DatacomAngular js presentation at Datacom
Angular js presentation at DatacomDavid Xi Peng Yang
 

What's hot (20)

MVVM Light Toolkit Works Great, Less Complicated
MVVM Light ToolkitWorks Great, Less ComplicatedMVVM Light ToolkitWorks Great, Less Complicated
MVVM Light Toolkit Works Great, Less Complicated
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
 
Mortal Kombat! ASP.NET MVC vs ASP.NET Webforms – ASP.NET MVC is amazing
Mortal Kombat! ASP.NET MVC vs ASP.NET Webforms – ASP.NET MVC is amazingMortal Kombat! ASP.NET MVC vs ASP.NET Webforms – ASP.NET MVC is amazing
Mortal Kombat! ASP.NET MVC vs ASP.NET Webforms – ASP.NET MVC is amazing
 
Sexy Architecting. VIPER: MVP on steroids
Sexy Architecting. VIPER: MVP on steroidsSexy Architecting. VIPER: MVP on steroids
Sexy Architecting. VIPER: MVP on steroids
 
ASP .Net MVC 5
ASP .Net MVC 5ASP .Net MVC 5
ASP .Net MVC 5
 
[@NaukriEngineering] MVVM in iOS
[@NaukriEngineering] MVVM in iOS[@NaukriEngineering] MVVM in iOS
[@NaukriEngineering] MVVM in iOS
 
MV(C, mvvm) in iOS and ReactiveCocoa
MV(C, mvvm) in iOS and ReactiveCocoaMV(C, mvvm) in iOS and ReactiveCocoa
MV(C, mvvm) in iOS and ReactiveCocoa
 
Angular js anupama
Angular js anupamaAngular js anupama
Angular js anupama
 
Introduction of angular js
Introduction of angular jsIntroduction of angular js
Introduction of angular js
 
Viper architecture
Viper architectureViper architecture
Viper architecture
 
ASP.NET MVC 3
ASP.NET MVC 3ASP.NET MVC 3
ASP.NET MVC 3
 
Itroducing Angular JS
Itroducing Angular JSItroducing Angular JS
Itroducing Angular JS
 
From mvc to viper
From mvc to viperFrom mvc to viper
From mvc to viper
 
Angular JS Indtrodution
Angular JS IndtrodutionAngular JS Indtrodution
Angular JS Indtrodution
 
KnockOutjs from Scratch
KnockOutjs from ScratchKnockOutjs from Scratch
KnockOutjs from Scratch
 
What's new in asp.net mvc 4
What's new in asp.net mvc 4What's new in asp.net mvc 4
What's new in asp.net mvc 4
 
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
 
Introduction to WPF and MVVM
Introduction to WPF and MVVMIntroduction to WPF and MVVM
Introduction to WPF and MVVM
 
Asp.net MVC training session
Asp.net MVC training sessionAsp.net MVC training session
Asp.net MVC training session
 
Angular js presentation at Datacom
Angular js presentation at DatacomAngular js presentation at Datacom
Angular js presentation at Datacom
 

Similar to Using a model view-view model architecture for iOS apps

Sitecore MVC (London User Group, April 29th 2014)
Sitecore MVC (London User Group, April 29th 2014)Sitecore MVC (London User Group, April 29th 2014)
Sitecore MVC (London User Group, April 29th 2014)Ruud van Falier
 
Sitecore MVC (User Group Conference, May 23rd 2014)
Sitecore MVC (User Group Conference, May 23rd 2014)Sitecore MVC (User Group Conference, May 23rd 2014)
Sitecore MVC (User Group Conference, May 23rd 2014)Ruud van Falier
 
Optimize CollectionView Scrolling
Optimize CollectionView ScrollingOptimize CollectionView Scrolling
Optimize CollectionView ScrollingAndrea Prearo
 
MVVM & Data Binding Library
MVVM & Data Binding Library MVVM & Data Binding Library
MVVM & Data Binding Library 10Clouds
 
Swift Tableview iOS App Development
Swift Tableview iOS App DevelopmentSwift Tableview iOS App Development
Swift Tableview iOS App DevelopmentKetan Raval
 
Say bye to Fragments with Conductor & Kotlin
Say bye to Fragments with Conductor & KotlinSay bye to Fragments with Conductor & Kotlin
Say bye to Fragments with Conductor & KotlinMiquel Beltran Febrer
 
Asp.Net Mvc
Asp.Net MvcAsp.Net Mvc
Asp.Net Mvcmicham
 
ASP.NET MVC Controllers & Actions
ASP.NET MVC Controllers & ActionsASP.NET MVC Controllers & Actions
ASP.NET MVC Controllers & Actionsonsela
 
Controllers & actions
Controllers & actionsControllers & actions
Controllers & actionsEyal Vardi
 
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller PatternDeveloping ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Patterngoodfriday
 
MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!Roberto Messora
 
Встреча №9. Будущее паттерна MVVM в iOS приложениях, Денис Лебедев
Встреча №9. Будущее паттерна MVVM в iOS приложениях, Денис ЛебедевВстреча №9. Будущее паттерна MVVM в iOS приложениях, Денис Лебедев
Встреча №9. Будущее паттерна MVVM в iOS приложениях, Денис ЛебедевCocoaHeads
 
MVVM with Databinding and Google's new ViewModel. UA Mobile 2017.
MVVM with Databinding and Google's new ViewModel. UA Mobile 2017.MVVM with Databinding and Google's new ViewModel. UA Mobile 2017.
MVVM with Databinding and Google's new ViewModel. UA Mobile 2017.UA Mobile
 

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

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

More from allanh0526

Digital authentication
Digital authenticationDigital authentication
Digital authenticationallanh0526
 
Integration of slather and jenkins
Integration of slather and jenkinsIntegration of slather and jenkins
Integration of slather and jenkinsallanh0526
 
How to generate code coverage reports in xcode with slather
How to generate code coverage reports in xcode with slatherHow to generate code coverage reports in xcode with slather
How to generate code coverage reports in xcode with slatherallanh0526
 
Unit testing in xcode 8 with swift
Unit testing in xcode 8 with swiftUnit testing in xcode 8 with swift
Unit testing in xcode 8 with swiftallanh0526
 
Ui testing in xcode
Ui testing in xcodeUi testing in xcode
Ui testing in xcodeallanh0526
 
How to work with dates and times in swift 3
How to work with dates and times in swift 3How to work with dates and times in swift 3
How to work with dates and times in swift 3allanh0526
 
ThingMaker in Swift
ThingMaker in SwiftThingMaker in Swift
ThingMaker in Swiftallanh0526
 
Automatic reference counting in Swift
Automatic reference counting in SwiftAutomatic reference counting in Swift
Automatic reference counting in Swiftallanh0526
 
Core data in Swfit
Core data in SwfitCore data in Swfit
Core data in Swfitallanh0526
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)allanh0526
 
From android/ java to swift (2)
From android/ java to swift (2)From android/ java to swift (2)
From android/ java to swift (2)allanh0526
 
From android/java to swift (1)
From android/java to swift (1)From android/java to swift (1)
From android/java to swift (1)allanh0526
 
Pipeline interface
Pipeline interfacePipeline interface
Pipeline interfaceallanh0526
 
Deploying artifacts to archiva
Deploying artifacts to archivaDeploying artifacts to archiva
Deploying artifacts to archivaallanh0526
 
Android httpclient
Android httpclientAndroid httpclient
Android httpclientallanh0526
 

More from allanh0526 (17)

Webp
WebpWebp
Webp
 
Digital authentication
Digital authenticationDigital authentication
Digital authentication
 
Integration of slather and jenkins
Integration of slather and jenkinsIntegration of slather and jenkins
Integration of slather and jenkins
 
How to generate code coverage reports in xcode with slather
How to generate code coverage reports in xcode with slatherHow to generate code coverage reports in xcode with slather
How to generate code coverage reports in xcode with slather
 
Unit testing in xcode 8 with swift
Unit testing in xcode 8 with swiftUnit testing in xcode 8 with swift
Unit testing in xcode 8 with swift
 
Ui testing in xcode
Ui testing in xcodeUi testing in xcode
Ui testing in xcode
 
How to work with dates and times in swift 3
How to work with dates and times in swift 3How to work with dates and times in swift 3
How to work with dates and times in swift 3
 
ThingMaker in Swift
ThingMaker in SwiftThingMaker in Swift
ThingMaker in Swift
 
Automatic reference counting in Swift
Automatic reference counting in SwiftAutomatic reference counting in Swift
Automatic reference counting in Swift
 
Core data in Swfit
Core data in SwfitCore data in Swfit
Core data in Swfit
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)
 
From android/ java to swift (2)
From android/ java to swift (2)From android/ java to swift (2)
From android/ java to swift (2)
 
From android/java to swift (1)
From android/java to swift (1)From android/java to swift (1)
From android/java to swift (1)
 
WebRTC
WebRTCWebRTC
WebRTC
 
Pipeline interface
Pipeline interfacePipeline interface
Pipeline interface
 
Deploying artifacts to archiva
Deploying artifacts to archivaDeploying artifacts to archiva
Deploying artifacts to archiva
 
Android httpclient
Android httpclientAndroid httpclient
Android httpclient
 

Recently uploaded

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 

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