Test iOS UserDefaults fallback and reset behavior on a cloud Mac

Test iOS UserDefaults fallback and reset behavior on a cloud Mac

Test iOS UserDefaults fallback and reset behavior on a cloud Mac

You test “Restore defaults” on a remote Mac desktop, but the toggle still has a value. Change the test execution order, and the result changes too. Before adding delays or forcing synchronization, check where the value comes from: a UserDefaults read may return a registered default, which does not mean persistent data is still present. Start by running a standalone Swift script on a cloud Mac, then carry the same contract over to iOS tests to pin down defaults, explicit overrides, and reset boundaries.

Define the settings read contract first

Define “Show hints” as enabled by default and “Retry count” as three by default. If a user explicitly disables hints or chooses zero retries, that choice must override the default. Removing a settings key should restore the default value.

register(defaults:) supplies fallback values in the registration domain; it does not write them to the app’s persistent domain. Ordinary reads search multiple domains, while persistentDomain(forName:) checks only the specified persistent domain. These operations answer different questions, so verify them with separate assertions.

“Readable” does not mean “persistently stored.” dictionaryRepresentation() is a merged view of the search domains, not proof that data has been written to disk.

Cover these four states in your test cases first: initial fallback, explicit override, single-key removal, and whole-domain reset. Do not check only the position of a UI toggle.

Run the baseline checks in an isolated suite

Run xcrun swift --version in Terminal to confirm that the tooling is available. Save the following code as defaults-contract.swift, then run xcrun swift defaults-contract.swift. No output and an exit code of zero mean that all preconditions passed; execution stops if any precondition fails.

A random suite name avoids picking up old data on a long-running machine. The script also generates unique key names to reduce registration-domain collisions within the same process. It touches only its own persistent domain, leaving the real app’s configuration untouched.

import Foundation

let token = UUID().uuidString
let suite = "local.defaults.contract." + token
guard let defaults = UserDefaults(suiteName: suite) else {
    fatalError("Unable to create defaults suite")
}

let enabled = token + ".hintsEnabled"
let retries = token + ".retryCount"
defer {
    defaults.removePersistentDomain(forName: suite)
}

defaults.register(defaults: [
    enabled: true,
    retries: 3
])

precondition(defaults.bool(forKey: enabled))
precondition(defaults.integer(forKey: retries) == 3)
precondition(defaults.persistentDomain(forName: suite)?[enabled] == nil)

defaults.set(false, forKey: enabled)
defaults.set(0, forKey: retries)
precondition(!defaults.bool(forKey: enabled))
precondition(defaults.integer(forKey: retries) == 0)
precondition(
    defaults.persistentDomain(forName: suite)?[enabled] as? Bool == false
)

defaults.removeObject(forKey: enabled)
precondition(defaults.bool(forKey: enabled))
precondition(defaults.persistentDomain(forName: suite)?[enabled] == nil)
precondition(defaults.integer(forKey: retries) == 0)

defaults.removePersistentDomain(forName: suite)
precondition(defaults.bool(forKey: enabled))
precondition(defaults.integer(forKey: retries) == 3)
precondition(defaults.persistentDomain(forName: suite)?[retries] == nil)

This script verifies Foundation behavior within the current process, not the timing of disk persistence across processes. It does not establish that reads after an app restart have passed, and it cannot replace execution inside the iOS sandbox.

Inject storage into the business layer

Business code that accesses UserDefaults.standard directly is difficult to isolate in tests. Have the settings repository accept a UserDefaults instance: pass the designated store in production and a newly created suite in tests. Register defaults centrally when initializing the repository, rather than scattering registration across different screens’ lifecycle methods.

Fallbacks must not override an explicit false value

Avoid logic that changes a value to true whenever a read returns false. bool(forKey:) can also return false when a key is missing, so a Boolean result cannot tell you whether the key exists. Once defaults are registered, an ordinary read returns the agreed fallback when needed.

Likewise, zero retries is a valid setting, not a sign that nothing has been configured. To determine whether a user has saved an option, check for its key in the target persistent domain. object(forKey:) also searches the registration domain, so it cannot answer that question.

The repository interface should also make clear whether a reset removes all settings or only UI preferences. If the same persistent domain contains other business flags, production code should remove keys using an allowlist rather than copying the test’s whole-domain cleanup.

Cover lifecycle boundaries in iOS tests

Convert the preconditions above into XCTest assertions and run them in an iOS test target. Give each test case its own suite and clean it up during teardown. Random key names are not a substitute for the app’s actual settings keys; business-layer tests should still operate on real keys through the repository interface.

Parallel tests need extra care: each suite does not have a completely independent copy of the registration domain. Registered keys with the same name can affect one another within the same process, so different suite names alone do not guarantee complete isolation. Run test cases that use the same key names serially, or inject a key prefix into the test repository.

For app restart behavior, create a separate integration test: write the settings, exit normally, relaunch, and then verify the values. A suite used by the test process does not automatically become the suite used by the app process; you need an explicit test entry point. Do not wrap a flow that has no completion condition in a fixed sleep, or use synchronize() to hide an incorrect choice of store.

Narrow down failures by their symptoms

If reads still return defaults after a reset, first check whether the persistent domain has been cleared; this is often the expected fallback behavior. If an explicit false value becomes true again, look for initialization logic based on Boolean values. If a test passes on its own but fails with the full suite, check for registration-key collisions and shared use of standard first.

When recording failures, retain only the suite name, test key, and expected type. Do not export the entire preferences dictionary. Final verification should cover both “what was removed” and “what reads return after removal.” Add a repeated-reset test as well to confirm that the second reset remains safe. The result is a reusable settings contract, not a UI state that happened to be correct once.

Frequently asked questions

Does register(defaults:) persist defaults to disk?

No. It supplies fallback values in the registration domain. Inspect persistentDomain(forName:) for persisted data rather than using dictionaryRepresentation().

Why can a setting still be read after removing its persistent domain?

Reads fall back to registered defaults. Assert both that business keys are absent from the persistent domain and that reads return the expected fallback values.

Validate your workflow on a dedicated Mac

Check the model, region, and rental term, then test it for a day. Live availability is shown in the console.