SlideShare a Scribd company logo
MVVM pattern in iOS development 
Denis Lebedev, 
iOS Hipster @ Wargaming 
! 
mailto: d_lebedev@wargaming.net 
linkedin: http://linkedin.com/in/dlebedev
Встреча №9. Будущее паттерна MVVM в iOS приложениях, Денис Лебедев
Agenda 
Wargaming Service Mobile Apps dept. 
MVC 
MVVM 
Development hints 
Reference
WARGAMING SERVICE MOBILE APPS
SMA department 
We make apps for user engagement 
Quality really matters 
We experiment a lot with new tools & technologies
Apps
MODEL-VIEW-CONTROLLER
MVC Diagram 
View 
Model 
Controller
Classical principles 
Loose coupling 
Model is decoupled; view/controller can listen to it’s changes 
View knows about model, can manipulate controller 
Controller knows everything and “does all the things” ©
View Controller responsibilities 
Owns & manages view’s state 
Acts as the datasource for tableviews 
Maps model’s properties to view values 
…
MASSIVE VIEW CONTROLLER
Real world MVC 
Controllers are ‘almost’ not reusable 
Controllers are large 
View is very tight to it’s controller 
Controllers are hard to unit test
Solving Massive Controller problems 
Separate object acting as tableview dataSource 
ConverterHelper, ‘MyFancyAttributeToStringHelper’, etc..
Testing 
Unit tests of controllers code is pain 
Sort of UI tests (Calabash, KIF) is required
Wrapping up 
MVC is not bad at all.
Wrapping up 
What can we do for better world?
MODEL-VIEW-VIEWMODEL
MVVM Diagram 
View/ 
ViewController ViewModel Model
MVVM Diagram 
Wait what? It’s the same!
Key differences with MVC 
ViewController owns it’s view model 
View model doesn’t know anything about controller
Key differences with MVC 
MVC MVVM 
View/ViewController 
ViewModel 
Model 
ViewController 
View 
Model
MVVM Models 
Can represent single domain entity or collection 
Responsible for fetching/storing data
MVVM Views 
Cocoa note: MVVM view = view + view controller 
view is stateless 
views/view controllers become smaller
MVVM View Models 
encapsulates all view data/properties and binds them to view 
validation logic 
actions
ReactiveCocoa 
Functional reactive paradigm in Cocoa world 
Fancy bindings 
Composes of sync/async events of any kind 
Mature, production-ready framework
ReactiveCocoa 
RAC(self, title) = RACObserve(self, viewModel.nickname);
ReactiveCocoa 
RAC(self, stringType) = [RACObserve(self, model.type) 
map:^id(NSNumber *v) { 
return v.intValue == 0 ? @"zero" : @"non-zero"; 
}];
Benefits 
We don’t need to to test the UI (actually we should) 
We can implement app logic without any UI 
view model is easy testable 
view model are (almost) platform independent
Platform agnostic code 
iPad / iPhone / OS X code sharing 
MVVM + Xamarin = shared Windows / OS X code
How we came to MVVM 
Already familiar with ReactiveCocoa 
Strong need in good internal testing 
Fresh project developed from scratch
DEVELOPMENT HINTS
What actually does view controller? 
Layout 
Animations 
Device rotation 
View transitions 
! 
All sensible state is stored in view model
Instantiation 
Every controller has viewModel property 
Some views may have separate view models 
Inject view model to controller during instantiation 
Inject view model’s important properties during instantiation
ViewModel interface 
RACSignals as model properties where possible 
RACSignal for data requests 
Model property (NSArray, domain object, etc.)
WPAFeaturesViewModel.h 
@interface WPAPlaneFeaturesViewModel : NSObject 
! 
@property (copy, nonatomic) NSArray *planeRows; 
! 
@property (strong, nonatomic, readonly) RACCommand *forwardCommand; 
@property (strong, nonatomic, readonly) RACSignal *forwardHidden; 
! 
@property (strong, nonatomic) RACSignal *nextPlaneTitle; 
! 
- (instancetype)initWithReferencePlane:(WOWPPlane *)plane 
classMates:(NSArray *)planes; 
! 
@end
ViewModel for tableviews 
ViewModel has “rows” property of type NSArray 
Row is some NSObject subclass with data very coupled to cell 
Formatters, etc. are applied to row class, not cell 
Controller binds to “rows” and reloads data after property changes
WPAPlaneRow.h 
@interface WPAPlaneRow : NSObject 
! 
@property (strong, nonatomic) WPAFeature *feature; 
@property (copy, nonatomic) NSString *value; 
@property (copy, nonatomic) NSString *grade; 
@property (copy, nonatomic) NSString *referenceGrade; 
! 
@end
Testing 
ViewModel tests are very obvious and atomic: 
State of model can be determined in any moment 
Property change affects view model internal state 
RACCommand changes view model state 
RACSignal pushes new state to subscribers
Real world testing 
Unit tests for view models 
Integration tests (for controllers) with KIF
IMPERATIVE VS DECLARATIVE
How to be functional and reactive 
Write declarative code instead of imperative 
Describe how properties are related to each other
Functional Reactive view model 
Almost all code is in constructor 
Describes how the view should work in terms of commands and 
properties
Functional Reactive view model 
The login button can be pressed when username and password aren’t 
blank 
! 
The error should be cleared after 5 seconds it was displayed
REFERENCE
Functional Reactive view model 
ReactiveCocoa https://github.com/ReactiveCocoa/ReactiveCocoa 
ReactiveViewModel https://github.com/ReactiveCocoa/ 
ReactiveViewModel 
! 
FRP on iOS https://leanpub.com/iosfrp 
! 
FunctionalReactivePixels https://github.com/AshFurrow/ 
FunctionalReactivePixels 
MVVMExample https://github.com/garnett/MVVMExample
THANK YOU!

More Related Content

PDF
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
PDF
MV(C, mvvm) in iOS and ReactiveCocoa
PDF
SpringMVC
PDF
Design & Development of Web Applications using SpringMVC
PDF
Workshop 16: EmberJS Parte I
PDF
Workshop 9: BackboneJS y patrones MVC
PDF
MVVM Light Toolkit Works Great, Less Complicated
PDF
Workshop 2: JavaScript Design Patterns
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
MV(C, mvvm) in iOS and ReactiveCocoa
SpringMVC
Design & Development of Web Applications using SpringMVC
Workshop 16: EmberJS Parte I
Workshop 9: BackboneJS y patrones MVC
MVVM Light Toolkit Works Great, Less Complicated
Workshop 2: JavaScript Design Patterns

What's hot (20)

PPTX
MVVM Lights
PPTX
Single Page Applications with AngularJS 2.0
PDF
AngularJS with RequireJS
ODP
Angularjs
PDF
Overview of the AngularJS framework
PPTX
Introduction to Angularjs
PDF
Web sockets in Angular
PDF
AngularJS introduction
PDF
Java server faces
PPTX
ASp.net Mvc 5
PPTX
5 angularjs features
PDF
Workshop 27: Isomorphic web apps with ReactJS
PDF
AngularJS 101 - Everything you need to know to get started
PPTX
Jsf presentation
PPTX
PDF
Spring MVC Intro / Gore - Nov NHJUG
PDF
Vue, vue router, vuex
PPTX
Spring mvc
PDF
Angularjs architecture
PDF
Break the monolith with (B)VIPER Modules
MVVM Lights
Single Page Applications with AngularJS 2.0
AngularJS with RequireJS
Angularjs
Overview of the AngularJS framework
Introduction to Angularjs
Web sockets in Angular
AngularJS introduction
Java server faces
ASp.net Mvc 5
5 angularjs features
Workshop 27: Isomorphic web apps with ReactJS
AngularJS 101 - Everything you need to know to get started
Jsf presentation
Spring MVC Intro / Gore - Nov NHJUG
Vue, vue router, vuex
Spring mvc
Angularjs architecture
Break the monolith with (B)VIPER Modules
Ad

Viewers also liked (14)

PDF
Александр Зимин — Мобильные интерфейсы будущего
PDF
UICollectionView — Александр Зимин
PDF
Александр Зимин — Анимация в iOS
PDF
Александр Зимин (Alexander Zimin) — UIViewController, откройся!
PDF
Как и зачем можно создать DSL на Python
PDF
Интерфейсы в Python
PDF
Rambler.iOS #5: VIPER a la Rambler
PPTX
Чем Python плох для стартапа?
PPTX
Sexy Architecting. VIPER: MVP on steroids
PPTX
VIPER - Design Pattern
PDF
Rambler.iOS #5: VIPER и Swift
PDF
Лекция 1. Начало.
PDF
"Почему язык Lua — это интересно?", Ник Заварицкий, (Mail.ru Group)
PPTX
Как создать эффективную презентацию?V 02
Александр Зимин — Мобильные интерфейсы будущего
UICollectionView — Александр Зимин
Александр Зимин — Анимация в iOS
Александр Зимин (Alexander Zimin) — UIViewController, откройся!
Как и зачем можно создать DSL на Python
Интерфейсы в Python
Rambler.iOS #5: VIPER a la Rambler
Чем Python плох для стартапа?
Sexy Architecting. VIPER: MVP on steroids
VIPER - Design Pattern
Rambler.iOS #5: VIPER и Swift
Лекция 1. Начало.
"Почему язык Lua — это интересно?", Ник Заварицкий, (Mail.ru Group)
Как создать эффективную презентацию?V 02
Ad

Similar to Встреча №9. Будущее паттерна MVVM в iOS приложениях, Денис Лебедев (20)

PDF
Jinal desai .net
PPT
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
PPTX
Valentine with AngularJS
PPTX
Training: MVVM Pattern
PDF
A4 from rad to mvc
PPTX
Spring MVC framework features and concepts
PPT
ASP.NET MVC Presentation
PPTX
Modern ASP.NET Webskills
PPTX
Spring mvc
PPT
MVC From Beginner to Advance in Indian Style by - Indiandotnet
PDF
Using a model view-view model architecture for iOS apps
PPTX
MVVM ( Model View ViewModel )
PDF
Model-View-Controller: Tips&Tricks
PDF
Swiz DAO
PDF
Spring MVC
PPTX
Asp.Net MVC Intro
PPTX
Mobile architecture problems and solutions.
PPTX
My perspective on MVP and architecture discussions
PDF
MVP Mix 2015 Leveraging MVVM on all Platforms
PPTX
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
Jinal desai .net
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
Valentine with AngularJS
Training: MVVM Pattern
A4 from rad to mvc
Spring MVC framework features and concepts
ASP.NET MVC Presentation
Modern ASP.NET Webskills
Spring mvc
MVC From Beginner to Advance in Indian Style by - Indiandotnet
Using a model view-view model architecture for iOS apps
MVVM ( Model View ViewModel )
Model-View-Controller: Tips&Tricks
Swiz DAO
Spring MVC
Asp.Net MVC Intro
Mobile architecture problems and solutions.
My perspective on MVP and architecture discussions
MVP Mix 2015 Leveraging MVVM on all Platforms
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS

More from CocoaHeads (12)

PDF
Дизайнер, разработчик, нет конфликта, нет драмы — Евгения Малкова
PDF
Эффективность на рубеже UITableView — Александр Зимин
PDF
Влад Ковташ — Yap Database
PDF
Push Notifications
PDF
Встреча №9. Алгоритмы и коллекции стандартных библиотек C++, C#, Java, Object...
PDF
Встреча №9. AudioBus: Эволюция звука, Данил Пархоменко
PDF
Встреча №8. NSIncrementalStore, или как заставить Core Data варить ваш собств...
PDF
Встреча №8. RESTful клиент — это просто. Тонкости использования RestKit, Миха...
PPTX
Встреча №8. Использование возможностей iOS 7 SDK, Ксения Покровская
PDF
Встреча №5. Взаимодействие между дизайнерами и разработчиками, Евгений Беляев
PDF
Встреча №5. Можно ли сделать дизайн без дизайнера? Александр Киров
PDF
Встреча №5. Звук и ресурсы iOS в realtime, Константин Платов
Дизайнер, разработчик, нет конфликта, нет драмы — Евгения Малкова
Эффективность на рубеже UITableView — Александр Зимин
Влад Ковташ — Yap Database
Push Notifications
Встреча №9. Алгоритмы и коллекции стандартных библиотек C++, C#, Java, Object...
Встреча №9. AudioBus: Эволюция звука, Данил Пархоменко
Встреча №8. NSIncrementalStore, или как заставить Core Data варить ваш собств...
Встреча №8. RESTful клиент — это просто. Тонкости использования RestKit, Миха...
Встреча №8. Использование возможностей iOS 7 SDK, Ксения Покровская
Встреча №5. Взаимодействие между дизайнерами и разработчиками, Евгений Беляев
Встреча №5. Можно ли сделать дизайн без дизайнера? Александр Киров
Встреча №5. Звук и ресурсы iOS в realtime, Константин Платов

Recently uploaded (20)

PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Nekopoi APK 2025 free lastest update
PPTX
ai tools demonstartion for schools and inter college
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
Digital Strategies for Manufacturing Companies
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
Transform Your Business with a Software ERP System
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PPTX
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
AI in Product Development-omnex systems
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PPTX
ISO 45001 Occupational Health and Safety Management System
PPTX
Online Work Permit System for Fast Permit Processing
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
L1 - Introduction to python Backend.pptx
How to Migrate SBCGlobal Email to Yahoo Easily
Nekopoi APK 2025 free lastest update
ai tools demonstartion for schools and inter college
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Digital Strategies for Manufacturing Companies
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Transform Your Business with a Software ERP System
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Design an Analysis of Algorithms II-SECS-1021-03
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
How Creative Agencies Leverage Project Management Software.pdf
AI in Product Development-omnex systems
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
ISO 45001 Occupational Health and Safety Management System
Online Work Permit System for Fast Permit Processing
How to Choose the Right IT Partner for Your Business in Malaysia
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Softaken Excel to vCard Converter Software.pdf
L1 - Introduction to python Backend.pptx

Встреча №9. Будущее паттерна MVVM в iOS приложениях, Денис Лебедев

  • 1. MVVM pattern in iOS development Denis Lebedev, iOS Hipster @ Wargaming ! mailto: d_lebedev@wargaming.net linkedin: http://linkedin.com/in/dlebedev
  • 3. Agenda Wargaming Service Mobile Apps dept. MVC MVVM Development hints Reference
  • 5. SMA department We make apps for user engagement Quality really matters We experiment a lot with new tools & technologies
  • 8. MVC Diagram View Model Controller
  • 9. Classical principles Loose coupling Model is decoupled; view/controller can listen to it’s changes View knows about model, can manipulate controller Controller knows everything and “does all the things” ©
  • 10. View Controller responsibilities Owns & manages view’s state Acts as the datasource for tableviews Maps model’s properties to view values …
  • 12. Real world MVC Controllers are ‘almost’ not reusable Controllers are large View is very tight to it’s controller Controllers are hard to unit test
  • 13. Solving Massive Controller problems Separate object acting as tableview dataSource ConverterHelper, ‘MyFancyAttributeToStringHelper’, etc..
  • 14. Testing Unit tests of controllers code is pain Sort of UI tests (Calabash, KIF) is required
  • 15. Wrapping up MVC is not bad at all.
  • 16. Wrapping up What can we do for better world?
  • 18. MVVM Diagram View/ ViewController ViewModel Model
  • 19. MVVM Diagram Wait what? It’s the same!
  • 20. Key differences with MVC ViewController owns it’s view model View model doesn’t know anything about controller
  • 21. Key differences with MVC MVC MVVM View/ViewController ViewModel Model ViewController View Model
  • 22. MVVM Models Can represent single domain entity or collection Responsible for fetching/storing data
  • 23. MVVM Views Cocoa note: MVVM view = view + view controller view is stateless views/view controllers become smaller
  • 24. MVVM View Models encapsulates all view data/properties and binds them to view validation logic actions
  • 25. ReactiveCocoa Functional reactive paradigm in Cocoa world Fancy bindings Composes of sync/async events of any kind Mature, production-ready framework
  • 26. ReactiveCocoa RAC(self, title) = RACObserve(self, viewModel.nickname);
  • 27. ReactiveCocoa RAC(self, stringType) = [RACObserve(self, model.type) map:^id(NSNumber *v) { return v.intValue == 0 ? @"zero" : @"non-zero"; }];
  • 28. Benefits We don’t need to to test the UI (actually we should) We can implement app logic without any UI view model is easy testable view model are (almost) platform independent
  • 29. Platform agnostic code iPad / iPhone / OS X code sharing MVVM + Xamarin = shared Windows / OS X code
  • 30. How we came to MVVM Already familiar with ReactiveCocoa Strong need in good internal testing Fresh project developed from scratch
  • 32. What actually does view controller? Layout Animations Device rotation View transitions ! All sensible state is stored in view model
  • 33. Instantiation Every controller has viewModel property Some views may have separate view models Inject view model to controller during instantiation Inject view model’s important properties during instantiation
  • 34. ViewModel interface RACSignals as model properties where possible RACSignal for data requests Model property (NSArray, domain object, etc.)
  • 35. WPAFeaturesViewModel.h @interface WPAPlaneFeaturesViewModel : NSObject ! @property (copy, nonatomic) NSArray *planeRows; ! @property (strong, nonatomic, readonly) RACCommand *forwardCommand; @property (strong, nonatomic, readonly) RACSignal *forwardHidden; ! @property (strong, nonatomic) RACSignal *nextPlaneTitle; ! - (instancetype)initWithReferencePlane:(WOWPPlane *)plane classMates:(NSArray *)planes; ! @end
  • 36. ViewModel for tableviews ViewModel has “rows” property of type NSArray Row is some NSObject subclass with data very coupled to cell Formatters, etc. are applied to row class, not cell Controller binds to “rows” and reloads data after property changes
  • 37. WPAPlaneRow.h @interface WPAPlaneRow : NSObject ! @property (strong, nonatomic) WPAFeature *feature; @property (copy, nonatomic) NSString *value; @property (copy, nonatomic) NSString *grade; @property (copy, nonatomic) NSString *referenceGrade; ! @end
  • 38. Testing ViewModel tests are very obvious and atomic: State of model can be determined in any moment Property change affects view model internal state RACCommand changes view model state RACSignal pushes new state to subscribers
  • 39. Real world testing Unit tests for view models Integration tests (for controllers) with KIF
  • 41. How to be functional and reactive Write declarative code instead of imperative Describe how properties are related to each other
  • 42. Functional Reactive view model Almost all code is in constructor Describes how the view should work in terms of commands and properties
  • 43. Functional Reactive view model The login button can be pressed when username and password aren’t blank ! The error should be cleared after 5 seconds it was displayed
  • 45. Functional Reactive view model ReactiveCocoa https://github.com/ReactiveCocoa/ReactiveCocoa ReactiveViewModel https://github.com/ReactiveCocoa/ ReactiveViewModel ! FRP on iOS https://leanpub.com/iosfrp ! FunctionalReactivePixels https://github.com/AshFurrow/ FunctionalReactivePixels MVVMExample https://github.com/garnett/MVVMExample