Delegation Pattern Flashcards
The delegation pattern is a variation of another pattern known as:
Decorator
Why do we specify the delegate’s type as a protocol?
To restrict only the objects that conform to the protocol from being assigned to the delegate property
TF: A design pattern is a general, reusable solution to a commonly occurring problem within a given context, regardless of the particular domain.
True
Generally, why should the delegate property be marked as weak?
To prevent reference cycles when the delegate and owner reference each other
TF: A design pattern is a code snippet that you can add to your project.
False
What is the base class for all objective c classes?
NSObject
TF: You can assign a delegate both in code and in Interface Builder
True
Why can we not implement optional protocol requirements?
Optional protocol requirements are an objective c construct and are currently unavailable in Swift
What problems does delegation solve?
Avoiding tight coupling of objects Modifying behavior and appearance without the need to subclass objects Allowing tasks to be handed off to an arbitrary object.
What exactly is a design pattern?
A design pattern is a general, reusable solution to a commonly occurring problem within a given context, regardless of the particular domain.
What the purpose of using a delegate? Example
Delegation is a design pattern that enables a class or structure to hand off (or delegate) some of its responsibilities to an instance of another type.
protocol HorseRaceDelegate: class { func race(_ race: Race, didStartAt time: Date) func addLapLeader(_ horse: Horse, forLap lap: Int, atTime time: Date) func race(_ race: Race, didEndAt time: Date, withWinner winner: Horse) }
class Race { weak var delegate: HorseRaceDelegate?
func updateLeader() { delegate?.addLapLeader(horse, forLap: horse.currentLap, atTime: Date())
}
}