Default values for UserDefaults
UserDefaults (NSUserDefaults
) is a go-to database for saving users' preferences over application behavior.
What is UserDefaults
?
UserDefaults
is a simple key-value store that allows you to save small amounts of data such as user preferences, settings, and other application state information. It is commonly used to store user settings, such as the user's preferred language, theme, or notification preferences.
Use Case: UserDefaults.register
let userDefaults = UserDefaults.standard
userDefaults.register(
defaults: [
"selectedPokemon": "Pikachu",
"pokemonCanEvolve": true
]
)
userDefaults.bool(forKey: "pokemonCanEvolve") // true.
Warning: The
register(defaults:)
method only sets the default values if the key does not exist in the user defaults, it will not save the default values to the user defaults. Therefore, you should call this method each time your app launches to ensure that the default values are set.
Caveats
- UserDefaults saves data in a local plist file on disk.
This means that the user can access and modify the data if they have access to the device, therefore it is not suitable for storing sensitive information such as passwords or tokens. - Registering default values will not save the default values to disk, therefore you should call this method each time your app launches to ensure that the default values are set.
- UserDefaults is not suitable for large data storage; consider using Core Data for that purpose.
NSUbiquitousKeyValueStore
which is the cloud-enabledUserDefaults
that can be used to synchronize data between devices using iCloud, has a limit of 1MB for the total size of the data, and a limit of 1024 keys.
Wrap up
UserDefaults is a simple way to store small amounts of data such as user preferences, settings, and other application state information. It is not suitable for storing sensitive information or large amounts of data.
Resources:
https://developer.apple.com/documentation/foundation/userdefaults
Read more
- Aurora Editor • 5 minutes reading time.
- Simplifying App Onboarding with OnboardingKit • 5 minutes reading time.
- Understanding reducers in Swift • 4 minutes reading time.
Share
Share Mastodon Twitter LinkedIn Facebook