Junior — Middle
What dispatch mechanism is used to extend functionality?
sobes.tech AI
Answer from AI
To extend functionality in iOS, the mechanism of dynamic dispatch is often used. This means that the method call is determined at runtime, not at compile time.
In particular, Objective-C uses a message passing mechanism, where a method call is sent to an object as a message, and the object decides which method to execute.
In Swift, dynamic dispatch is used for methods declared with the dynamic keyword or in classes that inherit from NSObject.
This allows:
- Overriding methods in subclasses,
- Using mechanisms such as swizzling,
- Extending class behavior without changing the source code.
Example in Swift:
class Base {
dynamic func greet() {
print("Hello from Base")
}
}
class Sub: Base {
override func greet() {
print("Hello from Sub")
}
}
let obj: Base = Sub()
obj.greet() // Outputs: Hello from Sub
Here, the call to greet() is determined at runtime, which is the essence of dynamic dispatch.