SlideShare ist ein Scribd-Unternehmen logo
1 von 46
Downloaden Sie, um offline zu lesen
Delegateless
Coordinators
Or yet… Event Based Coordinators
About me - Tales Pinheiro de Andrade
!@talesp, tales.andrade@concrete.com.br
!MSc Computer Science
!iOS Chapter Leader at Concrete
!CocoaHeads São Paulo Chapter Leader, CocoaHeads Brasil supporter
!C developer since 2003
!iOS since 2010
!Objective-C developer since 2007, Swift since 2015
Sumary
Content
!MVC Problems
!Introduction to Coordinators
!Delegation
!Base solution
!Chain of Responsibility
!Delegateless Coordinators
MVC Problems
MVC Problems
Responsibilities
Dependency Injection
Navigation Flow
• Layout
• Model-View binding
• Subview management
• User Input/Interaction
• Data
• Fetching
• Transformation
• Persistency
• Error Handling
• Navigation Flow
MVC Problems
Responsibilities
Dependency Injection
Navigation Flow
• Core Data/Realm
• Network
• Cache
• SomethingManager
• Frameworks de DI
• Typhon
• Kraken
• Perform
• SwiftDependencyInjection
• Swinject
MVC Problems
Responsibilities
Dependency Injection
Navigation Flow
Navigation Flow
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier !== "showDetail" {
if let indexPath = tableView.indexPathForSelectedRow {
let object = fetchedResultsController.object(at: indexPath)
let controller = (segue.destination as! UINavigationController)
.topViewController as! DetailViewController
controller.detailItem = object
}
}
}
Introduction to
Coordinators
So what is a coordinator?
A coordinator is an object that bosses one or more view
controllers around. Taking all of the driving logic out of
your view controllers, and moving that stuff one layer
up is gonna make your life a lot more awesome.
Coordinators Redux
(Soroush Khanlou)
So what is a coordinator?
The Coordinator is a PONSO, like all great objects. For
something like Instagram’s photo creation flow, we could
have a PhotoCreationCoordinator. The app
coordinator could spawn a new one, and pass it the
root view controller so that it could present the first
view controller in the flow.
The Coordinator

(Soroush Khanlou)
Delegation
Delegation
Delegation is a way to make composition as powerful for reuse
as inheritance. In delegation, two objects are involved in
handling a request: a receiving object delegates operations to
its delegate. This is analogous to subclasses deferring requests
to parent classes. But with inheritance, an inherited operation
can always refer to the receiving object through the this
member variable in C++ and self in Smalltalk. To achieve the
same effect with delegation, the receiver passes itself to the
delegate to let the delegated operation refer to the receiver.
Delegation: Knight Rider & RoboCop
Let’s start with a story: Once upon a time, there was a man with no name.
Knight Industries decided that if this man were given guns and wheels and
booster rockets, he would be the perfect crime-fighting tool. First they
thought, “Let’s subclass him and override everything we need to add the
guns and wheels and booster rockets.” The problem was that to subclass
Michael Knight, they needed to wire his insides to the guns, wheels, and
booster rockets – a time-consuming task requiring lots of specialized
knowledge. So instead, Knight Industries created a helper object, the
Knight Industries 2000, or “KITT,” a well-equipped car designed to assist
Michael Knight in a variety of crime- fighting situations.
Delegation: Super Máquina e RoboCop
While approaching the perimeter of an arms dealer’s compound, Michael
Knight would say, “KITT, I need to get to the other side of that wall.” KITT
would then blast a big hole in the wall with a small rocket. After destroying
the wall, KITT would return control to Michael, who would charge through
the rubble and capture the arms dealer.
Note how creating a helper object is different from the RoboCop
approach. RoboCop was a man subclassed and extended. The RoboCop
project involved dozens of surgeons who extended the man into a fighting
machine. This is the approach taken by many object-oriented frameworks.
Delegation: Super Máquina e RoboCop
In the Cocoa framework, many objects are extended in the Knight
Industries way – by supplying them with helper objects. In this section, you
are going to provide the speech synthesizer with a type of helper object
called a delegate.
From Cocoa Programming for OS X: The Big Nerd Ranch Guide
MVC-C · Injecting
Coordinator pattern in
UIKit
Taking the first step towards clean and minimal
app architecture in iOS app means freeing your
view controllers from the burden of dealing with
other controllers.
Implementation
Responder objects—that is, instances of UIResponder—
constitute the event-handling backbone of a UIKit app.
Many key objects are also responders, including the
UIApplication object, UIViewController objects, and all
UIView objects (which includes UIWindow). As events
occur, UIKit dispatches them to your app's responder
objects for handling.
UIResponder
Documentation
UIEvent
UIResponder children
View Controller
Implementação
In addition to handling events, UIKit responders also
manage the forwarding of unhandled events to other
parts of your app. If a given responder does not
handle an event, it forwards that event to the next
event in the responder chain. UIKit manages the
responder chain dynamically, using predefined rules to
determine which object should be next to receive an
event. For example, a view forwards events to its
superview, and the root view of a hierarchy forwards
events to its view controller.
UIResponder
Documentation
UIEvent
UIResponder children
View Controller
Implementação
UIResponder
Documentation
UIEvent
UIResponder children
View Controller
Implementação
UIResponder
Documentation
UIEvent
UIResponder children
View Controller
Implementação
UIResponder
Documentation
UIEvent
UIResponder children
View Controller
Implementação
UIResponder
Documentation
UIEvent
UIResponder children
View Controller
Implementação
UIResponder
Documentation
UIEvent
UIResponder children
View Controller
UIResponder children
open class UIView : UIResponder
open class UIViewController : UIResponder
open class UIWindow : UIView
class AppDelegate : UIResponder
open class UIApplication : UIResponder
Implementation - UIResponder
extension UIResponder {
public var coordinatingResponder: UIResponder? {
return next
}
}
extension UIResponder {
func messageTemplate(args: Whatever, sender: Any?) {
coordinatingResponder!?.messageTemplate(args: args, sender: sender)
}
}
extension UIResponder {
func cartBuyNow(_ product: Product, sender: Any?) { … }
func cartAdd(product: Product, color: ColorBox,
sender: Any?, completion: @escaping (Bool, Int) !-> Void) { … }
}
Chain of
Responsibility
Chain-of-Responsibility
In object-oriented design, the chain-of-responsibility pattern is a
design pattern consisting of a source of command objects and a
series of processing objects. Each processing object contains logic
that defines the types of command objects that it can handle; the rest
are passed to the next processing object in the chain. A mechanism
also exists for adding new processing objects to the end of this chain.
Thus, the chain of responsibility is an object oriented version of the
if ... else if ... else if ....... else ... endif idiom, with the benefit that the
condition–action blocks can be dynamically rearranged and
reconfigured at runtime.
Delegateless
Coordinators
Our solution
There are several kinds of events, including touch
events, motion events, remote-control events, and
press events. To handle a specific type of event, a
responder must override the corresponding
methods. For example, to handle touch events, a
responder implements the touchesBegan(_:with:),
touchesMoved(_:with:), touchesEnded(_:with:), and
touchesCancelled(_:with:) methods. In the case of
touches, the responder uses the event information
provided by UIKit to track changes to those touches
and to update the app's interface appropriately.
Remembering
Events
Defining Events
Protocol
Base implementation
Child management
Event handling
Defining Events
protocol AppEventType { }
protocol AppEventSubType { }
protocol AppEvent {
var type: AppEventType { get }
var subtype: AppEventSubType? { get }
}
Defining Events
protocol AppEvent { }
protocol AppEvent { }
public protocol CoordinatorProtocol: AnyObject, NSObjectProtocol {
var identifier: String { get }
var parent: CoordinatorProtocol? { get set }
var childCoordinators: [String: CoordinatorProtocol] { get }
var handlers: [String: (AppEvent) !-> Void] { get }
func start(with completion: @escaping () !-> Void)
func stop(with completion: @escaping () !-> Void)
func startChild(coordinator: CoordinatorProtocol, completion: @escaping () !-> Void)
func stopChild(coordinator: CoordinatorProtocol, completion: @escaping () !-> Void)
func target<T: AppEvent>(forEvent event: T) !-> CoordinatorProtocol?
func handle<T: AppEvent>(event: T) throws
func add<T: AppEvent>(eventType: T.Type, handler: @escaping (T) !-> Void)
func canHandle<T: AppEvent>(event: T) !-> Bool
}
CoordinatorProtocol Protocol
Base implementation
open class Coordinator: NSObject, CoordinatorProtocol {
public var parent: CoordinatorProtocol?
public var childCoordinators: [String : CoordinatorProtocol] = [:]
public weak var rootViewController: UIViewController?
public init(rootViewController: UIViewController?) {
self.rootViewController = rootViewController
}
open func start(with completion: @escaping () !-> Void = {}) {
self.rootViewController!?.parentCoordinator = self
completion()
}
open func stop(with completion: @escaping () !-> Void = {}) {
self.rootViewController!?.parentCoordinator = nil
completion()
}
Child management
open class Coordinator: NSObject, CoordinatorProtocol {
open func startChild(coordinator: CoordinatorProtocol,
completion: @escaping () !-> Void = {}) {
childCoordinators[coordinator.identifier] = coordinator
coordinator.parent = self
coordinator.start(with: completion)
}
public func stopChild(coordinator: CoordinatorProtocol,
completion: @escaping () !-> Void = {}) {
coordinator.parent = nil
coordinator.stop { [unowned self] in
self.childCoordinators.removeValue(forKey: coordinator.identifier)
completion()
}
}
Event handling
open class Coordinator: NSObject, CoordinatorProtocol {
public final func add<T>(eventType: T.Type,
handler: @escaping (T) !-> Void) where T : AppEvent {
handlers[String(reflecting: eventType)] = { event in
guard let realEV = event as? T else { return }
handler(realEV)
}
}
public final func handle<T: AppEvent>(event: T) throws {
let target = self.target(forEvent: event)
guard let handler = target!?.handlers[String(reflecting: type(of: event))] else {
throw AppEventError.eventNotHandled(event)
}
handler(event)
}
Event handling - helper functions
open class Coordinator: NSObject, CoordinatorProtocol {
public final func canHandle<T: AppEvent>(event: T) !-> Bool {
return handlers[String(reflecting: type(of: event))] !!= nil
}
public func target<T: AppEvent>(forEvent event: T) !-> CoordinatorProtocol? {
guard self.canHandle(event: event) !!= true else { return self }
var next = self.parent
while next!?.canHandle(event: event) !== false {
next = next!?.parent
}
return next
}
Event handling - helper functions
enum SignEvent: AppEvent {
case signIn
case signUp
}
enum SignInEvent: AppEvent {
typealias Username = String
typealias Password = String
case signIn(Username, Password)
case emptyUsernameOrPassword
}
Event handling - helper functions
override func start(with completion: @escaping () !-> Void = {}) {
self.add(eventType: SignEvent.self) { [weak self] event in
switch event {
case .signIn:
guard let navigationCoordinator = self!?.navigationCoordinator else {
fatalError("something went wrong")
}
let childCoordinator = SignInCoordinator(rootViewController: navigationCoordinator.rootViewController)
navigationCoordinator.startChild(coordinator: childCoordinator)
case .signUp: !// Start a child coordinator, go to some view controller or do something else…
}
}
self.add(eventType: SignInEvent.self) { [weak self] event in
switch event {
case .emptyUsernameOrPassword:!// treat error? show alert?
case let .signIn(username, password):
print("Auth with Username: (username) - password: (password)")
guard let navigationCoordinator = self!?.navigationCoordinator else {
fatalError("super.handle(event: event, withSender: self)")
}
self!?.stopChild(coordinator: navigationCoordinator)
guard let tabBarCoordinator = self!?.setupTabCoordinator() else { return }
self!?.startChild(coordinator: tabBarCoordinator)
}
}
super.start(with: completion)
}
AppCoordinator
SignCoordinator
SignInCoordinator
SignInViewController
SignUpCoordinator
SignUpViewController
TabBarCoordinator
ProductListCoordinator
UINavigationController
ProductListViewController ProductDetailViewController
ShoppingCartCoordinator
ShoppingCartViewController
ProfileCoordinator
ProfileViewController
DEMO TIME
See here:
https://github.com/talesp/DelegatelessCoordinators
Thank you
GitHub.com/talesp/DelegatelessCoordinators
@talesp
tales.andrade@concrete.com.br
N Ó S M O V E M O S O M U N D O .
RIO SÃO PAULO BH RECIFE
Centro
Av. Presidente Wilson, 231 
29º andar
(21) 2240-2030
Cidade Monções
Av. Nações Unidas, 11.541 
3º andar

(11) 4119-0449
Savassi
Av. Getúlio Vargas, 671 
Sala 800 - 8º andar
(31) 3360-8900
Ilha do Leite
Rua Sen. José Henrique, 199
2º andar
(81) 3018-6299
W W W. C O N C R E T E . C O M . B R

Weitere ähnliche Inhalte

Ähnlich wie Delegateless Coordinators - take 2

Jeff English: Demystifying Module Development - How to Extend Titanium
Jeff English: Demystifying Module Development - How to Extend TitaniumJeff English: Demystifying Module Development - How to Extend Titanium
Jeff English: Demystifying Module Development - How to Extend TitaniumAxway Appcelerator
 
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav DukhinFwdays
 
Application Frameworks: The new kids on the block
Application Frameworks: The new kids on the blockApplication Frameworks: The new kids on the block
Application Frameworks: The new kids on the blockRichard Lord
 
Itb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinItb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinGavin Pickin
 
Managed Extensibility Framework (MEF)
Managed Extensibility Framework (MEF)Managed Extensibility Framework (MEF)
Managed Extensibility Framework (MEF)Mohamed Meligy
 
Vilius Lukošius - Decomposing distributed monolith with Node.js (WIX.com)
Vilius Lukošius - Decomposing distributed monolith with Node.js (WIX.com)Vilius Lukošius - Decomposing distributed monolith with Node.js (WIX.com)
Vilius Lukošius - Decomposing distributed monolith with Node.js (WIX.com)Agile Lietuva
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideVisual Engineering
 
OpenWhisk Under the Hood -- London Oct 16 2016
OpenWhisk Under the Hood -- London Oct 16 2016OpenWhisk Under the Hood -- London Oct 16 2016
OpenWhisk Under the Hood -- London Oct 16 2016Stephen Fink
 
From User Action to Framework Reaction
From User Action to Framework ReactionFrom User Action to Framework Reaction
From User Action to Framework ReactionJonas Bandi
 
Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications Juliana Lucena
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteRavi Bhadauria
 
From User Action to Framework Reaction
From User Action to Framework ReactionFrom User Action to Framework Reaction
From User Action to Framework Reactionjbandi
 
A tour through Swift attributes
A tour through Swift attributesA tour through Swift attributes
A tour through Swift attributesMarco Eidinger
 
Riacon swiz
Riacon swizRiacon swiz
Riacon swizntunney
 
"Universal programming recipes", Kateryna Trofimenko
"Universal programming recipes", Kateryna Trofimenko"Universal programming recipes", Kateryna Trofimenko
"Universal programming recipes", Kateryna TrofimenkoBadoo Development
 
Universal programming recipes​ - Ekaterina Trofimenko - Women In Technology
Universal programming recipes​ - Ekaterina Trofimenko - Women In TechnologyUniversal programming recipes​ - Ekaterina Trofimenko - Women In Technology
Universal programming recipes​ - Ekaterina Trofimenko - Women In TechnologyBadoo
 
React Native custom components
React Native custom componentsReact Native custom components
React Native custom componentsJeremy Grancher
 

Ähnlich wie Delegateless Coordinators - take 2 (20)

Jeff English: Demystifying Module Development - How to Extend Titanium
Jeff English: Demystifying Module Development - How to Extend TitaniumJeff English: Demystifying Module Development - How to Extend Titanium
Jeff English: Demystifying Module Development - How to Extend Titanium
 
iOS Development (Part 2)
iOS Development (Part 2)iOS Development (Part 2)
iOS Development (Part 2)
 
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
 
Application Frameworks: The new kids on the block
Application Frameworks: The new kids on the blockApplication Frameworks: The new kids on the block
Application Frameworks: The new kids on the block
 
Itb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinItb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin Pickin
 
Managed Extensibility Framework (MEF)
Managed Extensibility Framework (MEF)Managed Extensibility Framework (MEF)
Managed Extensibility Framework (MEF)
 
Vilius Lukošius - Decomposing distributed monolith with Node.js (WIX.com)
Vilius Lukošius - Decomposing distributed monolith with Node.js (WIX.com)Vilius Lukošius - Decomposing distributed monolith with Node.js (WIX.com)
Vilius Lukošius - Decomposing distributed monolith with Node.js (WIX.com)
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native Side
 
OpenWhisk Under the Hood -- London Oct 16 2016
OpenWhisk Under the Hood -- London Oct 16 2016OpenWhisk Under the Hood -- London Oct 16 2016
OpenWhisk Under the Hood -- London Oct 16 2016
 
From User Action to Framework Reaction
From User Action to Framework ReactionFrom User Action to Framework Reaction
From User Action to Framework Reaction
 
Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
 
From User Action to Framework Reaction
From User Action to Framework ReactionFrom User Action to Framework Reaction
From User Action to Framework Reaction
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 
A tour through Swift attributes
A tour through Swift attributesA tour through Swift attributes
A tour through Swift attributes
 
Riacon swiz
Riacon swizRiacon swiz
Riacon swiz
 
"Universal programming recipes", Kateryna Trofimenko
"Universal programming recipes", Kateryna Trofimenko"Universal programming recipes", Kateryna Trofimenko
"Universal programming recipes", Kateryna Trofimenko
 
Universal programming recipes​ - Ekaterina Trofimenko - Women In Technology
Universal programming recipes​ - Ekaterina Trofimenko - Women In TechnologyUniversal programming recipes​ - Ekaterina Trofimenko - Women In Technology
Universal programming recipes​ - Ekaterina Trofimenko - Women In Technology
 
React Native custom components
React Native custom componentsReact Native custom components
React Native custom components
 
GWT MVP Case Study
GWT MVP Case StudyGWT MVP Case Study
GWT MVP Case Study
 

Mehr von Tales Andrade

Debugging tips and tricks - coders on beers Santiago
Debugging tips and tricks -  coders on beers SantiagoDebugging tips and tricks -  coders on beers Santiago
Debugging tips and tricks - coders on beers SantiagoTales Andrade
 
Swift na linha de comando
Swift na linha de comandoSwift na linha de comando
Swift na linha de comandoTales Andrade
 
Debugging tips and tricks
Debugging tips and tricksDebugging tips and tricks
Debugging tips and tricksTales Andrade
 
Usando POP com Programação Funcional
Usando POP com Programação FuncionalUsando POP com Programação Funcional
Usando POP com Programação FuncionalTales Andrade
 
Swift!.opcionais.oh!.my()?!?
Swift!.opcionais.oh!.my()?!?Swift!.opcionais.oh!.my()?!?
Swift!.opcionais.oh!.my()?!?Tales Andrade
 
Debugging fast track
Debugging fast trackDebugging fast track
Debugging fast trackTales Andrade
 

Mehr von Tales Andrade (7)

Debugging tips and tricks - coders on beers Santiago
Debugging tips and tricks -  coders on beers SantiagoDebugging tips and tricks -  coders on beers Santiago
Debugging tips and tricks - coders on beers Santiago
 
Swift na linha de comando
Swift na linha de comandoSwift na linha de comando
Swift na linha de comando
 
Debugging tips and tricks
Debugging tips and tricksDebugging tips and tricks
Debugging tips and tricks
 
Usando POP com Programação Funcional
Usando POP com Programação FuncionalUsando POP com Programação Funcional
Usando POP com Programação Funcional
 
Swift!.opcionais.oh!.my()?!?
Swift!.opcionais.oh!.my()?!?Swift!.opcionais.oh!.my()?!?
Swift!.opcionais.oh!.my()?!?
 
Debugging fast track
Debugging fast trackDebugging fast track
Debugging fast track
 
Tales@tdc
Tales@tdcTales@tdc
Tales@tdc
 

Kürzlich hochgeladen

Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptNANDHAKUMARA10
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoordharasingh5698
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Arindam Chakraborty, Ph.D., P.E. (CA, TX)
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapRishantSharmaFr
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01KreezheaRecto
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Standamitlee9823
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfKamal Acharya
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756dollysharma2066
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxJuliansyahHarahap1
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 

Kürzlich hochgeladen (20)

Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 

Delegateless Coordinators - take 2

  • 1.
  • 3. About me - Tales Pinheiro de Andrade !@talesp, tales.andrade@concrete.com.br !MSc Computer Science !iOS Chapter Leader at Concrete !CocoaHeads São Paulo Chapter Leader, CocoaHeads Brasil supporter !C developer since 2003 !iOS since 2010 !Objective-C developer since 2007, Swift since 2015
  • 4. Sumary Content !MVC Problems !Introduction to Coordinators !Delegation !Base solution !Chain of Responsibility !Delegateless Coordinators
  • 6. MVC Problems Responsibilities Dependency Injection Navigation Flow • Layout • Model-View binding • Subview management • User Input/Interaction • Data • Fetching • Transformation • Persistency • Error Handling • Navigation Flow
  • 7. MVC Problems Responsibilities Dependency Injection Navigation Flow • Core Data/Realm • Network • Cache • SomethingManager • Frameworks de DI • Typhon • Kraken • Perform • SwiftDependencyInjection • Swinject
  • 9. Navigation Flow override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier !== "showDetail" { if let indexPath = tableView.indexPathForSelectedRow { let object = fetchedResultsController.object(at: indexPath) let controller = (segue.destination as! UINavigationController) .topViewController as! DetailViewController controller.detailItem = object } } }
  • 11. So what is a coordinator? A coordinator is an object that bosses one or more view controllers around. Taking all of the driving logic out of your view controllers, and moving that stuff one layer up is gonna make your life a lot more awesome. Coordinators Redux (Soroush Khanlou)
  • 12. So what is a coordinator? The Coordinator is a PONSO, like all great objects. For something like Instagram’s photo creation flow, we could have a PhotoCreationCoordinator. The app coordinator could spawn a new one, and pass it the root view controller so that it could present the first view controller in the flow. The Coordinator
 (Soroush Khanlou)
  • 13.
  • 15. Delegation Delegation is a way to make composition as powerful for reuse as inheritance. In delegation, two objects are involved in handling a request: a receiving object delegates operations to its delegate. This is analogous to subclasses deferring requests to parent classes. But with inheritance, an inherited operation can always refer to the receiving object through the this member variable in C++ and self in Smalltalk. To achieve the same effect with delegation, the receiver passes itself to the delegate to let the delegated operation refer to the receiver.
  • 16. Delegation: Knight Rider & RoboCop Let’s start with a story: Once upon a time, there was a man with no name. Knight Industries decided that if this man were given guns and wheels and booster rockets, he would be the perfect crime-fighting tool. First they thought, “Let’s subclass him and override everything we need to add the guns and wheels and booster rockets.” The problem was that to subclass Michael Knight, they needed to wire his insides to the guns, wheels, and booster rockets – a time-consuming task requiring lots of specialized knowledge. So instead, Knight Industries created a helper object, the Knight Industries 2000, or “KITT,” a well-equipped car designed to assist Michael Knight in a variety of crime- fighting situations.
  • 17. Delegation: Super Máquina e RoboCop While approaching the perimeter of an arms dealer’s compound, Michael Knight would say, “KITT, I need to get to the other side of that wall.” KITT would then blast a big hole in the wall with a small rocket. After destroying the wall, KITT would return control to Michael, who would charge through the rubble and capture the arms dealer. Note how creating a helper object is different from the RoboCop approach. RoboCop was a man subclassed and extended. The RoboCop project involved dozens of surgeons who extended the man into a fighting machine. This is the approach taken by many object-oriented frameworks.
  • 18. Delegation: Super Máquina e RoboCop In the Cocoa framework, many objects are extended in the Knight Industries way – by supplying them with helper objects. In this section, you are going to provide the speech synthesizer with a type of helper object called a delegate. From Cocoa Programming for OS X: The Big Nerd Ranch Guide
  • 19.
  • 20. MVC-C · Injecting Coordinator pattern in UIKit Taking the first step towards clean and minimal app architecture in iOS app means freeing your view controllers from the burden of dealing with other controllers.
  • 21. Implementation Responder objects—that is, instances of UIResponder— constitute the event-handling backbone of a UIKit app. Many key objects are also responders, including the UIApplication object, UIViewController objects, and all UIView objects (which includes UIWindow). As events occur, UIKit dispatches them to your app's responder objects for handling. UIResponder Documentation UIEvent UIResponder children View Controller
  • 22. Implementação In addition to handling events, UIKit responders also manage the forwarding of unhandled events to other parts of your app. If a given responder does not handle an event, it forwards that event to the next event in the responder chain. UIKit manages the responder chain dynamically, using predefined rules to determine which object should be next to receive an event. For example, a view forwards events to its superview, and the root view of a hierarchy forwards events to its view controller. UIResponder Documentation UIEvent UIResponder children View Controller
  • 28. UIResponder children open class UIView : UIResponder open class UIViewController : UIResponder open class UIWindow : UIView class AppDelegate : UIResponder open class UIApplication : UIResponder
  • 29. Implementation - UIResponder extension UIResponder { public var coordinatingResponder: UIResponder? { return next } } extension UIResponder { func messageTemplate(args: Whatever, sender: Any?) { coordinatingResponder!?.messageTemplate(args: args, sender: sender) } } extension UIResponder { func cartBuyNow(_ product: Product, sender: Any?) { … } func cartAdd(product: Product, color: ColorBox, sender: Any?, completion: @escaping (Bool, Int) !-> Void) { … } }
  • 31. Chain-of-Responsibility In object-oriented design, the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain. Thus, the chain of responsibility is an object oriented version of the if ... else if ... else if ....... else ... endif idiom, with the benefit that the condition–action blocks can be dynamically rearranged and reconfigured at runtime.
  • 33. There are several kinds of events, including touch events, motion events, remote-control events, and press events. To handle a specific type of event, a responder must override the corresponding methods. For example, to handle touch events, a responder implements the touchesBegan(_:with:), touchesMoved(_:with:), touchesEnded(_:with:), and touchesCancelled(_:with:) methods. In the case of touches, the responder uses the event information provided by UIKit to track changes to those touches and to update the app's interface appropriately. Remembering Events Defining Events Protocol Base implementation Child management Event handling
  • 34. Defining Events protocol AppEventType { } protocol AppEventSubType { } protocol AppEvent { var type: AppEventType { get } var subtype: AppEventSubType? { get } }
  • 36. protocol AppEvent { } public protocol CoordinatorProtocol: AnyObject, NSObjectProtocol { var identifier: String { get } var parent: CoordinatorProtocol? { get set } var childCoordinators: [String: CoordinatorProtocol] { get } var handlers: [String: (AppEvent) !-> Void] { get } func start(with completion: @escaping () !-> Void) func stop(with completion: @escaping () !-> Void) func startChild(coordinator: CoordinatorProtocol, completion: @escaping () !-> Void) func stopChild(coordinator: CoordinatorProtocol, completion: @escaping () !-> Void) func target<T: AppEvent>(forEvent event: T) !-> CoordinatorProtocol? func handle<T: AppEvent>(event: T) throws func add<T: AppEvent>(eventType: T.Type, handler: @escaping (T) !-> Void) func canHandle<T: AppEvent>(event: T) !-> Bool } CoordinatorProtocol Protocol
  • 37. Base implementation open class Coordinator: NSObject, CoordinatorProtocol { public var parent: CoordinatorProtocol? public var childCoordinators: [String : CoordinatorProtocol] = [:] public weak var rootViewController: UIViewController? public init(rootViewController: UIViewController?) { self.rootViewController = rootViewController } open func start(with completion: @escaping () !-> Void = {}) { self.rootViewController!?.parentCoordinator = self completion() } open func stop(with completion: @escaping () !-> Void = {}) { self.rootViewController!?.parentCoordinator = nil completion() }
  • 38. Child management open class Coordinator: NSObject, CoordinatorProtocol { open func startChild(coordinator: CoordinatorProtocol, completion: @escaping () !-> Void = {}) { childCoordinators[coordinator.identifier] = coordinator coordinator.parent = self coordinator.start(with: completion) } public func stopChild(coordinator: CoordinatorProtocol, completion: @escaping () !-> Void = {}) { coordinator.parent = nil coordinator.stop { [unowned self] in self.childCoordinators.removeValue(forKey: coordinator.identifier) completion() } }
  • 39. Event handling open class Coordinator: NSObject, CoordinatorProtocol { public final func add<T>(eventType: T.Type, handler: @escaping (T) !-> Void) where T : AppEvent { handlers[String(reflecting: eventType)] = { event in guard let realEV = event as? T else { return } handler(realEV) } } public final func handle<T: AppEvent>(event: T) throws { let target = self.target(forEvent: event) guard let handler = target!?.handlers[String(reflecting: type(of: event))] else { throw AppEventError.eventNotHandled(event) } handler(event) }
  • 40. Event handling - helper functions open class Coordinator: NSObject, CoordinatorProtocol { public final func canHandle<T: AppEvent>(event: T) !-> Bool { return handlers[String(reflecting: type(of: event))] !!= nil } public func target<T: AppEvent>(forEvent event: T) !-> CoordinatorProtocol? { guard self.canHandle(event: event) !!= true else { return self } var next = self.parent while next!?.canHandle(event: event) !== false { next = next!?.parent } return next }
  • 41. Event handling - helper functions enum SignEvent: AppEvent { case signIn case signUp } enum SignInEvent: AppEvent { typealias Username = String typealias Password = String case signIn(Username, Password) case emptyUsernameOrPassword }
  • 42. Event handling - helper functions override func start(with completion: @escaping () !-> Void = {}) { self.add(eventType: SignEvent.self) { [weak self] event in switch event { case .signIn: guard let navigationCoordinator = self!?.navigationCoordinator else { fatalError("something went wrong") } let childCoordinator = SignInCoordinator(rootViewController: navigationCoordinator.rootViewController) navigationCoordinator.startChild(coordinator: childCoordinator) case .signUp: !// Start a child coordinator, go to some view controller or do something else… } } self.add(eventType: SignInEvent.self) { [weak self] event in switch event { case .emptyUsernameOrPassword:!// treat error? show alert? case let .signIn(username, password): print("Auth with Username: (username) - password: (password)") guard let navigationCoordinator = self!?.navigationCoordinator else { fatalError("super.handle(event: event, withSender: self)") } self!?.stopChild(coordinator: navigationCoordinator) guard let tabBarCoordinator = self!?.setupTabCoordinator() else { return } self!?.startChild(coordinator: tabBarCoordinator) } } super.start(with: completion) }
  • 46. N Ó S M O V E M O S O M U N D O . RIO SÃO PAULO BH RECIFE Centro Av. Presidente Wilson, 231  29º andar (21) 2240-2030 Cidade Monções Av. Nações Unidas, 11.541  3º andar
 (11) 4119-0449 Savassi Av. Getúlio Vargas, 671  Sala 800 - 8º andar (31) 3360-8900 Ilha do Leite Rua Sen. José Henrique, 199 2º andar (81) 3018-6299 W W W. C O N C R E T E . C O M . B R