Millist mõju avaldab @objc dynamic annotatsiooni kasutamine koodis?
sobes.tech AI
Vastus AI-lt
The @objc dynamic annotation in Swift performs two main functions:
-
@objc — makes a method or property accessible to the Objective-C runtime. This is necessary if you want to use dynamic dispatching, interact with Objective-C APIs such as KVO (Key-Value Observing), selectors, or old code.
-
dynamic — forces the compiler to use dynamic dispatching via the Objective-C runtime, instead of static or inline optimizations. This allows, for example, intercepting method calls, which is necessary for KVO.
Together, @objc dynamic is commonly used for properties and methods that need to support dynamic change observation (KVO) or be accessible from Objective-C.
Example:
class Person: NSObject {
@objc dynamic var name: String = ""
}
let person = Person()
var observation = person.observe(\.name, options: [.new]) { object, change in
print("Name changed to \(change.newValue ?? "")")
}
person.name = "Ivan" // triggers the observer
Without @objc dynamic, KVO will not work, as the mechanism relies on the Objective-C runtime and dynamic dispatching.