iOS
NSUserDefaults
dictionary
Swift
iOS development

Delete all keys from a NSUserDefaults dictionary iOS

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

If you want to wipe everything your app has stored in UserDefaults, the cleanest approach is to remove the app's persistent domain instead of manually deleting keys one by one. That is useful for logout flows, test reset buttons, and "factory reset" features, but you should be clear about whether you want to remove all defaults or only app-specific session data.

What "delete all keys" really means

UserDefaults is not literally one Swift dictionary you mutate directly. It is a persistent preferences store scoped by domains, with your app's bundle identifier typically acting as the main domain. Because of that, the correct API for clearing everything is domain-based, not "iterate through a dictionary and remove every entry."

For most apps, the relevant domain name is the bundle identifier:

swift
1import Foundation
2
3func resetAllDefaults() {
4    guard let bundleID = Bundle.main.bundleIdentifier else {
5        return
6    }
7
8    let defaults = UserDefaults.standard
9    defaults.removePersistentDomain(forName: bundleID)
10}

That removes every value stored by your app in the standard defaults domain. It is the most direct answer when the real requirement is "make the app behave like a fresh install with respect to UserDefaults."

Reset only what you own when possible

Even though removing the whole domain works, it is not always the best product decision. Some values are often better preserved across logout or reset events, such as onboarding completion, theme preference, or a one-time migration marker.

A safer pattern is to group volatile keys and clear only those keys:

swift
1import Foundation
2
3enum DefaultsKey: String, CaseIterable {
4    case accessToken
5    case refreshToken
6    case cachedProfileName
7    case lastWorkspaceID
8}
9
10func clearSessionDefaults() {
11    let defaults = UserDefaults.standard
12
13    for key in DefaultsKey.allCases {
14        defaults.removeObject(forKey: key.rawValue)
15    }
16}

This gives you much better control over reset behavior. In real apps, "delete all keys" is often an overcorrection for what is really a session cleanup problem.

If you stored a dictionary under one key

Sometimes the question is actually about a dictionary value stored under a single defaults key rather than the entire defaults store. In that case, remove that one object or replace it with an empty dictionary.

swift
1import Foundation
2
3func clearCachedDictionary() {
4    let defaults = UserDefaults.standard
5    defaults.removeObject(forKey: "cachedFilters")
6}
7
8func replaceWithEmptyDictionary() {
9    let defaults = UserDefaults.standard
10    defaults.set([String: String](), forKey: "cachedFilters")
11}

Use removeObject(forKey:) when "no value exists" is the correct state. Use an empty dictionary only when downstream code expects the key to exist and treats an empty collection as meaningful.

Verify the reset behavior

It is easy to clear values and still think nothing happened because some settings are re-created at launch. The best way to verify the reset is to write a small check before and after the cleanup.

swift
1import Foundation
2
3func debugDefaultsState() {
4    let defaults = UserDefaults.standard
5    print(defaults.dictionaryRepresentation())
6}
7
8debugDefaultsState()
9resetAllDefaults()
10debugDefaultsState()

dictionaryRepresentation() is especially useful in debugging and tests because it shows the currently visible key-value pairs. You should still be careful not to dump sensitive values into production logs.

Timing and synchronization notes

Older code samples sometimes call synchronize() after removing defaults. That method is no longer the recommended tool for normal app logic. UserDefaults already manages persistence timing for you, and manually forcing sync is rarely needed.

If you are performing a logout reset followed immediately by navigation back to a signed-out screen, clearing defaults first and then rebuilding in-memory state is usually enough. The more important issue is consistency in your app state, not explicit disk flushing.

Common Pitfalls

  • Removing the entire defaults domain when the real requirement was only to clear session or cache keys.
  • Storing too much app state in UserDefaults and then needing a destructive reset to recover from model drift.
  • Replacing a missing value with an empty dictionary without checking what the rest of the app expects.
  • Logging the full defaults dictionary in production and leaking sensitive values during debugging.
  • Calling synchronize() out of habit even though normal UserDefaults writes already persist correctly.

Summary

  • To clear everything in your app's defaults, use removePersistentDomain(forName:) with the bundle identifier.
  • If the goal is logout or cache cleanup, prefer removing only the specific keys you own.
  • If you stored a dictionary under one key, remove that object rather than wiping the whole defaults domain.
  • Use dictionaryRepresentation() to verify behavior during development and tests.
  • Treat a full defaults reset as a deliberate product decision, not the default cleanup strategy.

Course illustration
Course illustration

All Rights Reserved.