Describe how to use Notifications in iOS.

Instruction: Explain the mechanism for using Notifications to pass data or messages between different parts of an iOS application.

Context: This question assesses in-process communication using Foundation NotificationCenter, including payload validation, delivery context and observer lifetime.

Updated

Official answer

For messages between components of one running app, use Foundation's NotificationCenter. Register for a named event, optionally filter its source object, and post a Notification with a documented payload. This is separate from user-visible local or push notifications handled by User Notifications.

Traditional post delivery to selector observers is synchronous on the posting thread. For the block observer API, a nil queue runs the block synchronously on that thread; a specified queue controls delivery. Do not assume posting dispatches work asynchronously or makes UI updates safe. Keep handlers short and arrange UI work on the main actor/thread.

This complete Foundation example uses a private center and synchronous, single-threaded delivery; it does not update UI:

import Foundation

let taskCompleted = Notification.Name("TaskCompleted")
final class TaskObserver: NSObject {
    private let center: NotificationCenter
    private(set) var lastTaskID: String?

    init(center: NotificationCenter, name: Notification.Name) {
        self.center = center
        super.init()
        center.addObserver(self, selector: #selector(receive(_:)),
                           name: name, object: nil)
    }

    @objc private func receive(_ notification: Notification) {
        guard let id = notification.userInfo?["taskId"] as? String else {
            return
        }
        lastTaskID = id
    }

    deinit { center.removeObserver(self) }
}

let center = NotificationCenter()
var observer: TaskObserver? = TaskObserver(center: center, name: taskCompleted)
center.post(name: taskCompleted, object: nil, userInfo: ["taskId": "1234"])
assert(observer?.lastTaskID == "1234")
observer = nil
center.post(name: taskCompleted, object: nil, userInfo: ["taskId": "5678"])

For a block-based observer, retain the returned observer token and remove that token when observation ends; avoid a block that strongly retains its owner indefinitely. Modern selector registrations have automatic cleanup on supported systems, but explicit removal still expresses an earlier observation boundary. Do not confuse the traditional block token with newer typed notification APIs that have different lifetime and concurrency rules.

Use notifications for decoupled broadcasts, not as an untyped substitute for every direct call. Define the name, payload types, thread/actor contract and observation lifetime, and test repeated registration and cleanup.

Sources

Apple: NotificationCenter; notification delivery.

Related Questions