What is the purpose of 'Delegates' in iOS?
Instruction: Describe the delegation pattern and its use in iOS app development.
Updated
Official answer
Delegation gives an object a collaborator that implements a protocol. The object calls that collaborator to report an event, request a decision or customize behavior without subclassing. The protocol defines the contract; it does not by itself define ownership, threading or delivery guarantees.
This complete synchronous example uses a class-bound protocol so the worker can hold its delegate weakly. The caller keeps the delegate alive:
protocol JobDelegate: AnyObject {
func jobDidFinish(value: Int)
}
final class Job {
weak var delegate: (any JobDelegate)?
func run() { delegate?.jobDidFinish(value: 7) }
}
final class Recorder: JobDelegate {
var values: [Int] = []
func jobDidFinish(value: Int) { values.append(value) }
}
let job = Job()
var recorder: Recorder? = Recorder()
job.delegate = recorder
job.run()
assert(recorder?.values == [7])
recorder = nil
assert(job.delegate == nil)
job.run() // No delegate, so no callback.
A weak delegate avoids extending the delegate's lifetime and can prevent an ownership cycle, but not all framework delegates have identical retention rules. Assigning a newly created object only to a weak property can make it disappear immediately. Check the API and keep an owner when needed.
For UIKit, UITextFieldDelegate can allow editing, evaluate a proposed replacement and respond to editing beginning or ending. A proposed replacement callback is not a universal notification for every programmatic text change. Use the documented control event, observation or explicit state update appropriate to the change. UIKit callbacks also have main-actor requirements; a custom delegate must document its own execution context.
Delegation usually represents one designated collaborator, whereas notifications suit multiple observers. Neither pattern automatically makes code more maintainable; test missing delegates, lifetime changes and callback order.
Swift protocols, ARC and closure cycles, Text field delegate contract
Related Questions
-
easy
-
medium
-
hard
-
hard