Test iOS notification observer lifecycles on a cloud Mac

Test iOS notification observer lifecycles on a cloud Mac

Test iOS notification observer lifecycles on a cloud Mac

If a page refreshes once when first opened but twice after you leave and return, the problem often lies not with the notification sender, but with a new observer being added on every visit. Developers who only have Windows can run this Foundation logic on a cloud Mac, verify the registration and removal contract in isolated tests, and then return to the iOS interface to check where those calls belong. No external services need to be connected.

Define the contract

Start with three rules: each relevant notification is handled exactly once; notifications with the same name from other senders are ignored; and posting another notification after observation has stopped no longer changes business state. Do not treat “it did not crash” as evidence that an observer has been released.

This article covers the block-based API that returns a token from addObserver(forName:object:queue:using:). You need to retain that token, not the business object itself. Passing the wrong object to the removal method may run without error while leaving the intended registration in place.

queue: nil does not guarantee execution on the main thread. The handler normally runs synchronously on the thread that posts the notification. Even when that synchronous callback has finished, any asynchronous work it started may still be running.

UI updates, notification subscriptions, and background work have three separate lifecycles. Verify each one independently before testing the handoffs between them. That makes failures easier to locate.

Set up the test fixture

Run the following in a terminal on a cloud Mac with the Xcode command line tools installed:

mkdir ObserverContract
cd ObserverContract
swift package init --type library
swift --version

Delete the generated sample test file and save the following code as Tests/ObserverContractTests/ObserverContractTests.swift. These tests create a dedicated notification center rather than using the global default center, so events with the same name from other tests cannot interfere.

import Foundation
import XCTest

final class Counter: @unchecked Sendable {
    private let lock = NSLock()
    private var storage = 0

    func increment() {
        lock.lock()
        defer { lock.unlock() }
        storage += 1
    }

    var value: Int {
        lock.lock()
        defer { lock.unlock() }
        return storage
    }
}

final class ObserverContractTests: XCTestCase {
    func testSenderAndRemoval() {
        let center = NotificationCenter()
        let name = Notification.Name("DocumentChanged")
        let sender = NSObject()
        let other = NSObject()
        let counter = Counter()

        let token = center.addObserver(
            forName: name,
            object: sender,
            queue: nil
        ) { _ in
            counter.increment()
        }
        defer { center.removeObserver(token) }

        center.post(name: name, object: other)
        XCTAssertEqual(counter.value, 0)

        center.post(name: name, object: sender)
        XCTAssertEqual(counter.value, 1)

        center.removeObserver(token)
        center.post(name: name, object: sender)
        XCTAssertEqual(counter.value, 1)
    }

    func testRegistrationsAreIndependent() {
        let center = NotificationCenter()
        let name = Notification.Name("DocumentChanged")
        let counter = Counter()

        let tokens = (0..<2).map { _ in
            center.addObserver(
                forName: name,
                object: nil,
                queue: nil
            ) { _ in
                counter.increment()
            }
        }
        defer { tokens.forEach { center.removeObserver($0) } }

        center.post(name: name, object: nil)
        XCTAssertEqual(counter.value, 2)
    }
}

Run swift test. The first test checks sender filtering and observer removal. The second demonstrates that registering twice creates two independent observers; the registrations are not merged automatically. The counter’s lock protects access across threads. The @unchecked Sendable declaration is valid only because all mutable state is accessed under that lock. Do not copy it onto business objects without equivalent synchronization.

Give registration a clear owner

A real screen usually needs an explicit owner for its subscription. Give that owner start() and stop() methods: the former returns immediately if a token already exists; the latter removes the observer and clears the token. Run both methods on the same executor or serial queue so that two calls cannot pass the nil check at the same time.

Inject the isolated test’s notification center into the owner through its initializer. Then add three sets of business-logic tests:

  • Call start() twice in succession, then post once. The business handler’s count must still be one.
  • Call start() and stop(), then post. The handler’s count must remain unchanged.
  • Start again after stopping, then post once. The handler’s count must increase by exactly one.

Do not register unconditionally on every view update. First decide whether observation should last “while the screen is visible” or “for the lifetime of the object,” then choose the appropriate lifecycle entry points. A subscription tied to visibility must stop when the screen is left; waiting for the object to be destroyed is not enough.

If the block needs to access the subscription owner, check its capture relationships. The notification center retains the callback, the callback may strongly retain the business object, and the business object stores the token. This can prevent the expected deinitialization cleanup from happening. Weak captures can reduce that retention, but they do not replace an explicit stop.

Separate asynchronous work

The assertions above hold because the tests do not post concurrently and delivery is synchronous. If the callback creates a Task, reading state immediately after post returns may give you the old value.

Asynchronous tests should wait for a business-level completion signal—for example, an XCTest expectation confirming that the result has been committed—rather than sleeping for a fixed duration. To test the cancellation boundary, pause the task with a controllable test barrier: trigger the notification, stop observing, and finally release the barrier. Then check whether the old task can still write back to state.

Removing an observer does not undo a callback that has already started, nor does it automatically cancel tasks spawned by that callback. If stopping must prevent further state updates, retain task handles and use cooperative cancellation, or validate the session generation when committing results. There must also be no new suspension point between that check and the commit; otherwise, an old result may still cross the boundary.

Keep the evidence

For each commit, record the toolchain version, the test exit code, and the names of any failing tests. Synchronous tests need no waiting period. If one fails intermittently, first check whether it has inadvertently switched back to the default notification center, shares a sender with other tests, or allows other tasks to post concurrently.

Sender filtering is based on object identity. The two separate NSObject instances in the test represent “the same event name, but different senders.” Do not confuse equal values with identical senders. If business identifiers need to pass between modules, validate those fields separately in the payload.

Finally, add the acceptance checklist to code review: Is registration idempotent? Who owns the token? Can the stop path actually be reached? Is asynchronous work cancelled separately? Do tests use an isolated notification center? Stabilize these boundaries before investigating duplicate UI refreshes, so that a deduplication patch does not conceal an ever-growing set of subscriptions.

Frequently asked questions

Does a nil queue guarantee delivery on the main thread?

No. A block observer normally executes synchronously on the posting thread. Explicitly hop to the main actor for UI updates and test that handoff separately.

Does removing an observer cancel tasks it already started?

No. Keep task handles for cooperative cancellation, or reject stale results using a session generation. Removing the observer does not undo work already launched.

Move your project to a cloud Mac

Rent a dedicated physical node and access the macOS desktop in your browser. Choose your configuration and billing period, then build your project in Xcode.

Build your project

Choose a configuration that fits your workload and compile and package your project on a dedicated cloud Mac.