About Observer Design Pattern
The Observer pattern is a behavioral design pattern that allows an object (subject) to notify other objects (observers) when its state changes. In iOS, this pattern is implemented through mechanisms like NotificationCenter, KVO (Key-Value Observing), and Combine.
Key Features
- One-to-many communication
- Loose coupling
- Runtime registration/deregistration
- Broadcast notifications
- Filter-based observation
Code Example
// Observer pattern examples in iOS
// 1. NotificationCenter
// Register for notifications
NotificationCenter.default.addObserver(
self,
selector: #selector(handleDataChange(_:)),
name: Notification.Name("DataDidChangeNotification"),
object: nil
)
// Post a notification
NotificationCenter.default.post(
name: Notification.Name("DataDidChangeNotification"),
object: nil,
userInfo: ["updatedData": newData]
)
// Handle notification
@objc func handleDataChange(_ notification: Notification) {
if let data = notification.userInfo?["updatedData"] {
// Update UI with new data
}
}
// Deregister when done
deinit {
NotificationCenter.default.removeObserver(self)
}
// 2. Key-Value Observing (KVO)
// Start observing
var observation: NSKeyValueObservation?
observation = object.observe(\.property) { object, change in
print("Property changed to: \(object.property)")
}
// Stop observing
observation?.invalidate()
// 3. Combine (iOS 13+)
import Combine
class ViewModel {
@Published var counter: Int = 0
}
// Using the publisher
let viewModel = ViewModel()
var cancellables = Set<AnyCancellable>()
viewModel.$counter
.sink { newValue in
print("Counter changed to: \(newValue)")
}
.store(in: &cancellables)
// Changing the value
viewModel.counter += 1