Member-only story
Objective-C Keywords in Swift
Dynamic or synthesize
I’ve been looking at some Objective-C keywords recently. Follow this article and see what I’ve learned!
Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 15.0, and Swift 5.9
Terminology:
synthesize: In Objective-C, @synthesize automatically generates the getter and setter methods for a property declared in the class interface.
dynamic: The @dynamic keyword in Objective-C tells the compiler that the accessor methods for a property will be provided dynamically at runtime, often through the Objective-C runtime features.
dynamic
@dynamic tells the compiler that the accessor methods are provided at runtime.
This is used to indicate that the accessor methods for a property (getter and setter) are implemented manually or will be provided at runtime, rather than being automatically synthesized by the compiler. This is often used in conjunction with runtime features or when integrating with other frameworks that require specific handling of property access.
final class MyClass: NSObject {
@objc dynamic func exampleMethod() {
print("Example Method")
}
}
let myObject = MyClass()
myObject.perform(#selector(myObject.exampleMethod))
Here exampleMethod
is exposed to the Objective-C runtime and so can be called dynamically using performSelector
.
Dynamic can also be used for property observing.
final class MyObservableClass: NSObject {
@objc dynamic var observableProperty: String = ""
}
let myObject = MyObservableClass()
myObject.observe(\.observableProperty, options: [.new]) { object, change in
print("Property changed to \(object.observableProperty)")
}
myObject.observableProperty = "New Value"
Here, observableProperty is marked as @objc dynamic, allowing it to be observed for changes using Key-Value Observing (KVO) which is a feature of the Objective-C runtime.
synthesize
@synthesize means that the compiler generates the getters and/or setters appropriate to match specifications given…