Custom events with NotificationCenter in iOS
NotificationCenter is built into Foundation and gives an iOS app a lightweight way to broadcast information between independent objects. A publisher posts a named notification; one or more subscribers observe it and react. This pattern suits UIKit projects, where a cart, account screen, or download manager may inform several components without linking them directly.
These custom events are entirely in-process. They differ from APNs push notifications and do not create a visible alert. The same core API handles a cart update, network result, or small piece of app state.
The examples suit an Australian product. A shopper in Brisbane might add an item while a checkout view in Melbourne updates its total and a badge in Sydney reflects the change. Local details matter too: prices can be displayed in AUD, dates often use day-month-year order, and timestamps must account for Sydney and Melbourne moving to AEDT while Brisbane remains on AEST.
Shared event buses without tight dependencies
NotificationCenter acts as a simple event broker. The publisher knows only the notification name and payload; it does not need references to every interested screen. Subscribers register for the events they understand, creating loose coupling between the code announcing something and the code responding to it.
The arrangement works best when an event reports a fact that has already happened: cartItemAdded, downloadFinished, or sessionExpired. It is weaker when subscribers must perform a chain of commands or establish hidden ordering. For a button action, text-field change, or one controller passing a result to another, a delegate, closure, or target-action relationship is easier to follow.
The trade-off is visibility. Direct calls expose dependencies, while a notification can hide important relationships inside subscriptions. A small shared coordinator, typed event names, and documented payloads keep that flexibility from becoming an unpredictable message maze.
Defining a stable event contract
Give every event a meaningful Notification.Name and define it in one place. A reverse-DNS raw value avoids collisions with other modules or app extensions that might publish similar names.
extension Notification.Name {
static let cartItemAdded =
Notification.Name("com.askaralmukhamet.CartItemAdded")
}
The name should describe the fact being broadcast, not tell another object what to do. A past-tense name such as cartItemAdded lets subscribers update a badge, analytics record, or confirmation banner. An imperative name such as addItemToCart suggests a command and can turn the notification centre into a global controller.
A typed payload keeps required fields together and lets subscribers use a safe cast:
struct CartItemAddedPayload {
let productID: String
let quantity: Int
}
Keep the payload small and relevant. If subscribers must filter by the sender, reserve object for that source and put the payload in userInfo. Otherwise, using object for the payload is simple and effective. Avoid scattered raw userInfo keys, because that replaces compile-time clarity with dictionary lookups.
Publishing events from UIKit
A producer can post an event after committing the corresponding model change. The method could live in a view controller, view model, repository, or coordinator:
private let eventBus: NotificationCenter
func addProductToCart(productID: String, quantity: Int = 1) {
let payload = CartItemAddedPayload(
productID: productID,
quantity: quantity
)
eventBus.post(name: .cartItemAdded, object: payload)
}
Injecting NotificationCenter makes the producer easier to test and allows an isolated centre for a test target. Although NotificationCenter.default works for small apps, a dependency prevents one test's notifications from reaching observers left behind by another test. It also makes the event dependency visible in initialisers.
Post only after the source of truth has changed. If adding an item fails validation or persistence, publishing cartItemAdded first would leave subscribers showing a state the app never accepted. There is no acknowledgement or return value from post, so the publisher must decide when the event represents completed work.
Keeping delivery safe for UIKit
Observers need the correct execution context. UIKit updates belong on the main thread, so a subscriber that changes a label, reloads a table, or presents an alert should use the main operation queue:
private var cartObserver: NSObjectProtocol?
private func observeCartEvents() {
cartObserver = eventBus.addObserver(
forName: .cartItemAdded,
object: nil,
queue: .main
) { [weak self] notification in
guard let payload = notification.object as? CartItemAddedPayload else {
return
}
self?.showItemAdded(payload.productID)
}
}
The chosen queue affects delivery, but it does not turn the closure into an isolated Swift actor. Code using modern concurrency should still respect @MainActor requirements and hop deliberately when necessary. Also, post does not wait for asynchronous UI work to finish, so do not use a notification as a barrier or assume every observer has updated by the next line.
Notification ordering is not a contract. One subscriber should not publish another event merely because it needs a sibling to run first; that creates fragile sequencing. If order genuinely matters, model it as explicit application state or work on a dedicated serial queue rather than coordinating through broadcasts.
Managing observer lifetime
Every closure-based registration returns an NSObjectProtocol token. Keep it for as long as the observer should receive events, then remove it when the owner is no longer active:
deinit {
if let observer = cartObserver {
eventBus.removeObserver(observer)
}
}
Capturing self weakly prevents the closure from unnecessarily prolonging the lifetime of a view controller, but weak capture does not replace cleanup. Always remove the token when the observation scope ends. Selector-based registration with addObserver(_:selector:name:object:) follows the observer object's lifetime on modern iOS releases, although explicit removal can still make ownership clearer.
An observer should ignore malformed payloads and unrelated notifications rather than force-casting blindly. This matters when object is nil and the observer listens to a shared event name. It is also wise to make handling repeatable, since an event may arrive after part of the screen has already updated. Notification Centre provides broadcast delivery, not the state guarantees of a database or view model.
Verifying event flow with Xcode
Unit tests can use a fresh NotificationCenter instance, which isolates the publisher and subscriber under test. An XCTest expectation confirms delivery and validates the payload:
func testCartItemAddedCarriesPayload() {
let centre = NotificationCenter()
let received = expectation(description: "Cart event received")
let observer = centre.addObserver(
forName: .cartItemAdded, object: nil, queue: nil
) { notification in
let payload = notification.object as? CartItemAddedPayload
XCTAssertEqual(payload?.productID, "coffee-blend")
XCTAssertEqual(payload?.quantity, 2)
received.fulfill()
}
defer { centre.removeObserver(observer) }
centre.post(
name: .cartItemAdded,
object: CartItemAddedPayload(productID: "coffee-blend", quantity: 2)
)
wait(for: [received], timeout: 1)
}
The publisher side benefits from a short checklist that can become assertions in different test cases:
Publisher checks
- The event uses a namespaced
Notification.Nameand documented payload. - The post occurs only after the underlying state change succeeds.
- The publishing queue and timing match the contract.
- Sensitive user data is not copied into
userInfo.
The subscriber side needs equally explicit checks:
Observer checks
- Unrelated or malformed notifications are ignored safely.
- UIKit work runs on the main thread.
- Closure tokens are retained and removed at the correct lifetime boundary.
- Duplicate delivery does not corrupt visible state.
Use Xcode's test navigator for these checks, then add a UI test only when visible behaviour matters. A UI test might add a product in one screen and confirm that a badge or total updates elsewhere. That coverage catches missing subscriptions that a publisher-only unit test would miss.
The principle to remember
Custom notifications are most valuable when they carry shared facts across a clear boundary. A cart, session, or download service can announce a change without owning every interested screen, while each subscriber remains responsible for its own reaction.
The contract matters as much as the mechanism. Use stable names, small typed payloads, deliberate queues, and explicit observer ownership. Keep truly local interactions with delegates, closures, or target-action, and reserve notifications for events with genuine app-wide relevance.
The point to remember is simple: publish facts with clear contracts, deliver them on the correct queue, and make observer ownership explicit.