ArchitectureMidMCQ
What is the Observer pattern and how is it used in iOS?
Test your knowledge:
Explanation & Code
Answer: The Observer pattern lets objects subscribe to events from another object without tight coupling. One-to-many event broadcasting.
iOS implementations:
// 1. Combine / @Published (modern, SwiftUI)
class ViewModel: ObservableObject {
@Published var count = 0
}
// Views automatically observe and re-render
// 2. NotificationCenter (app-wide broadcasts)
NotificationCenter.default.post(name: .userLoggedIn, object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(handleLogin),
name: .userLoggedIn, object: nil)
// 3. Delegate pattern (one-to-one observer)
protocol DownloadDelegate: AnyObject {
func didFinishDownload(url: URL)
}
class Downloader {
weak var delegate: DownloadDelegate?
}
// 4. KVO (Key-Value Observing) — mostly Objective-C legacy
Rate your understanding: