Sobes.tech
Junior — Middle

How does the use of the @objc annotation affect dynamic method dispatch in Objective-C and Swift?

sobes.tech AI

Answer from AI

The @objc annotation in Swift indicates to the compiler that this class, method, or property should be accessible from the Objective-C runtime. This means that such methods will participate in dynamic dispatch through the Objective-C mechanism — method calls will be resolved at runtime rather than at compile time.

Without @objc, Swift uses static dispatch (for example, for methods in structures or final classes), which improves performance but limits interaction with Objective-C.

Example:

class MyClass: NSObject {
    @objc func dynamicMethod() {
        print("Call via Objective-C runtime")
    }
}

let obj = MyClass()
let selector = #selector(MyClass.dynamicMethod)
if obj.responds(to: selector) {
    obj.perform(selector)
}

Here, @objc allows calling the method via a selector, which is only possible with dynamic dispatch in Objective-C.

How does the use of the @objc annotation affect… - sobes.tech