2.4 · NotificationCenter, KVO and Operation
Three older Foundation tools for “tell me when something happens” and “run this work in order”. They still show up in every UIKit codebase, and each has one sharp edge that interviews love.
Mental model. All three are loosely coupled by name or key path. That is their strength (nobody needs to know anybody) and their weakness (the compiler cannot help you).
NotificationCenter
Broadcast events, delivered synchronously, and the lifetime rules that cause leaks.
- How does NotificationCenter deliver a notification, and on which thread?
You register an observer for a Notification.Name, and anyone can post that name. Delivery is synchronous: post calls every matching observer one after another… - How do you avoid leaks and crashes with notification observers?
The block-based addObserver(forName:object:queue:using:) returns an opaque token. The center keeps your block alive until you call removeObserver(token), and… - How do you pass data in a notification safely?
A Notification carries a name, an optional object (usually the sender) and an optional userInfo dictionary of type [AnyHashable: Any]. That dictionary is… - NotificationCenter, delegate, closure or KVO: how do you choose?
Ask how many listeners and how much do they need to know each other. NotificationCenter is one-to-many with no knowledge of who listens: good for app-wide…
Key-value observing
Watching a property on an Objective-C-compatible object.
- How does KVO work in Swift, and why does it sometimes never fire?
Key-value observing lets you watch a property of an object: object.observe(\.name, options: [.new, .old]) { object, change in … }. It returns an…
Operation and OperationQueue
Dependencies, cancellation and where it sits next to GCD and async/await.
- What do Operation and OperationQueue give you that GCD does not, and where does async/await fit?
Operation models a unit of work as an object, so a queue can add dependencies (“run B after A”), priorities, a concurrency limit (maxConcurrentOperationCount)…
More in Foundation & stdlib
- 2.1 · Collections, indexing, Sequence and lazy
- 2.2 · Date, Calendar, Locale, TimeZone, FormatStyle
- 2.3 · URL, URLComponents, Data, FileManager
- 2.5 · JSON coder options, property lists, UserDefaults
- 2.6 · Bundle, resources, localization tables
- 2.7 · NSCache and locks
- 2.8 · Attributed strings, scanners, number formatters
- 2.9 · Bridging to Objective-C Foundation types