Can you name the main ways to implement the observer pattern?
sobes.tech AI
Answer from AI
Main ways to implement the observer pattern in iOS:
-
NotificationCenter — a system mechanism for broadcasting notifications. It allows objects to subscribe to notifications with a specific name and receive them when someone publishes such a notification.
-
KVO (Key-Value Observing) — a mechanism for observing changes to object properties. It automatically notifies when a property's value changes.
-
Delegate — a pattern where an object holds a reference to a delegate and calls delegate methods upon event occurrence.
-
Closure/Callback — passing closures (functions) to be called when the state changes.
-
Reactive frameworks (e.g., RxSwift) — use reactive programming for subscribing and handling events.
Example with NotificationCenter:
NotificationCenter.default.addObserver(self, selector: #selector(handleNotification), name: .myNotification, object: nil)
@objc func handleNotification(_ notification: Notification) {
print("Notification received")
}
NotificationCenter.default.post(name: .myNotification, object: nil)