UserDefaults.standard.set("someValue", forKey: "preferenceName") and read it back as an optional String? with UserDefaults.standard.string(forKey: "preferenceName"). In SwiftUI views, use @AppStorage("preferenceName") private var preferenceName = "" to read, persist, and update the UI automatically without manual calls.Why this happens
Apple’s preferences system stores lightweight key-value pairs—such as usernames, selected appearance modes, or onboarding flags—in a property list managed by the operating system. In Objective-C, this class is named NSUserDefaults. In Swift, Foundation bridges the same API as UserDefaults, and SwiftUI adds the @AppStorage property wrapper on top of it so views automatically refresh when a stored value changes.
Developers looking up NSUserDefaults examples frequently run into two legacy pitfalls. First, older Objective-C snippets almost always call synchronize immediately after saving a string. Apple deprecated synchronize because cfprefsd caches values in memory immediately and flushes changes to disk automatically at optimal intervals; forcing synchronous disk writes on the main thread only slows down your UI.
Second, Xcode autocomplete offers both set(_:forKey:) and setValue(_:forKey:) on UserDefaults. While they look nearly identical, setValue(_:forKey:) is a Key-Value Coding (KVC) method inherited from NSObject, not the standard UserDefaults setter. Passing keys that contain dots or start with @ to setValue(_:forKey:) can throw an uncaught Objective-C NSUnknownKeyException at runtime.
How to fix it
1. Save and read a String in Swift with UserDefaults
In UIKit controllers, view models, services, or background tasks, interact with UserDefaults.standard directly. Always write strings using set(_:forKey:) and read them back with string(forKey:), which safely returns nil if the key does not exist or holds a non-string value that cannot be converted.
import Foundation
enum PreferenceKey {
static let displayName = "user_display_name"
}
// Save a string
let nameToSave = "Taylor"
UserDefaults.standard.set(nameToSave, forKey: PreferenceKey.displayName)
// Read the string back later (returns String?)
if let savedName = UserDefaults.standard.string(forKey: PreferenceKey.displayName) {
print("Loaded name: \(savedName)")
}
If you want a fallback value when nothing has been saved yet, use the nil-coalescing operator (??) or register default values at app launch using register(defaults:):
import Foundation
// Register in-memory fallback defaults once at launch
UserDefaults.standard.register(defaults: [
PreferenceKey.displayName: "Guest"
])
// Returns "Guest" until a value is explicitly written
let currentName = UserDefaults.standard.string(forKey: PreferenceKey.displayName) ?? "Guest"
To delete a saved string, call removeObject(forKey:):
UserDefaults.standard.removeObject(forKey: PreferenceKey.displayName)
2. Bind a String directly to views in SwiftUI with @AppStorage
Inside a SwiftUI View, you do not need to read or write UserDefaults.standard manually. Mark a property with @AppStorage and provide the key string. SwiftUI reads the initial value from UserDefaults.standard, writes changes back whenever the property mutates, and invalidates the view whenever that key updates anywhere in your app.
import SwiftUI
struct ProfileSettingsView: View {
@AppStorage("user_display_name") private var displayName: String = ""
var body: some View {
Form {
TextField("Display Name", text: $displayName)
.textInputAutocapitalization(.words)
Text("Saved value: \(displayName.isEmpty ? "None" : displayName)")
.foregroundStyle(.secondary)
Button("Reset Name", role: .destructive) {
displayName = ""
}
}
}
}
If you need to distinguish between an empty string "" and a key that has never been set (nil), declare the property as an optional String? without a default string literal:
import SwiftUI
struct OnboardingBannerView: View {
@AppStorage("last_seen_version") private var lastSeenVersion: String?
var body: some View {
if lastSeenVersion == nil {
Button("Mark Onboarding Complete") {
lastSeenVersion = "2.0"
}
}
}
}
Setting lastSeenVersion = nil removes the key from UserDefaults entirely.
3. Share saved strings with Widgets and App Extensions
UserDefaults.standard writes to the sandboxed container of the running process. If your main iOS or macOS app saves a string to .standard, a WidgetKit extension, Share extension, or watchOS companion extension cannot read it—calling string(forKey:) in the extension will always return nil.
To share strings across targets:
- Open your project settings in Xcode and select your main app target.
- Go to Signing & Capabilities, click + Capability, and add App Groups.
- Create or select a group identifier (for example,
group.com.example.myapp) and enable the exact same App Group on your extension target. - Initialize
UserDefaultswithsuiteName:instead of.standard.
import Foundation
import SwiftUI
extension UserDefaults {
static let sharedSuite = UserDefaults(suiteName: "group.com.example.myapp")!
}
// In Swift services or Widget TimelineProvider
UserDefaults.sharedSuite.set("Updated status", forKey: "widget_headline")
let headline = UserDefaults.sharedSuite.string(forKey: "widget_headline")
// In SwiftUI views
struct SharedHeadlineView: View {
@AppStorage("widget_headline", store: .sharedSuite)
private var headline: String = "Default Headline"
var body: some View {
Text(headline)
}
}
4. Save and read an NSString in Objective-C
If you are maintaining an Objective-C class or bridging legacy Cocoa Touch code, use [NSUserDefaults standardUserDefaults] with setObject:forKey: and stringForKey:. Omit synchronize, as the system persists the in-memory cache automatically.
#import <Foundation/Foundation.h>
static NSString * const kPreferenceNameKey = @"preferenceName";
- (void)saveStringToDefaults:(NSString *)valueToSave {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:valueToSave forKey:kPreferenceNameKey];
}
- (nullable NSString *)loadStringFromDefaults {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
return [defaults stringForKey:kPreferenceNameKey];
}
Note that passing nil to setObject:forKey: on NSUserDefaults removes the stored entry cleanly without crashing, behaving identically to removeObjectForKey:.
How to prevent it
- Centralize your keys in constants: Define keys once on an
enumorextensioninstead of typing raw string literals across multiple files. One typo in a key silently causesstring(forKey:)to returnnil. - Use
set(_:forKey:), neversetValue(_:forKey:): Stick to the dedicatedUserDefaultsAPI so Key-Value Coding path parsing never intercepts characters like.or@in your key names. - Never store secrets in
UserDefaults: Values saved toUserDefaultsare stored in an unencrypted.plistfile inside the app container. Store passwords, OAuth access tokens, refresh tokens, and API secrets in the Keychain instead. - Keep stored strings small: The entire preferences property list is loaded into memory when accessed. Avoid dumping multi-megabyte JSON payloads or Base64-encoded images as strings into
UserDefaults; write large files toFileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)instead. - Remove
synchronize()from legacy code: LeavingUserDefaults.standard.synchronize()inside loops or view lifecycle methods triggers unnecessary disk I/O and Xcode deprecation warnings.
FAQ
Why does UserDefaults.standard.string(forKey:) return nil right after I saved a value?
Check that both calls use the exact same case-sensitive key string and the same UserDefaults instance. If you wrote the value in your main app using .standard and tried reading it inside a Widget or App Extension, .standard points to two separate sandboxed containers—switch both targets to UserDefaults(suiteName:) with a shared App Group.
Do I still need to call synchronize() before the app goes into the background?
No. UserDefaults updates its in-memory state immediately across all threads in your process, and the system daemon flushes changes to persistent storage automatically even if your app is suspended shortly afterward.
Can I use @AppStorage inside an @Observable class or ViewModel?
@AppStorage is designed specifically for SwiftUI View and App types and does not trigger observation updates cleanly inside @Observable classes. Inside an @Observable model, store a regular Swift property that calls UserDefaults.standard.set(_:forKey:) in didSet and reads its initial value from UserDefaults.standard.string(forKey:) in init().
Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.