Why UserDefaults: because some time we need to save small amount of data like setting, status or record in our app thats why we can use this in the place of Core Data. This can support for saving data type like Bool
, Dictionary
, Int
, String
, Data
, Array
.
Here’s an example of setting some values:
let defaults = UserDefaults.standard
defaults.set("Denis Andreev", forKey: "name")
let name = defaults.string(forKey: "name") ?? ""
Why I used here name . This the key using for saving and retrieving data. Every data we can store with the unique key other wise it will replace old data with new one.
You can also use the nil-coalescing operator ??
to provide a default value.
defaults.set(true, forKey: “isUserlogin”)
let status = defaults.bool(forKey: “isUserlogin”) ?? false
When you set values like that, they become permanent – you can quit the app then re-launch and they’ll still be there, so it’s the ideal way to store app configuration data. As an advance warning, you might find some old tutorials recommend calling the synchronize()
method to force your data to save, but Apple has asked us not to do that for some years now.
As mentioned, you can use UserDefaults to store arrays and dictionaries, like this:
let array = ["Apple", "Banana"]
defaults.set(array, forKey: "Fruits")
let dict = ["Name": "Denis", "Country": "Russia"]
defaults.set(dict, forKey: "UserData")
When it comes to reading data back, it’s still easy but has an important proviso: UserDefaults will return a default value if the setting can’t be found. You need to know what these default values are so that you don’t confuse them with real values that you set. Here they are:
With that in mind, you can read values back like this:
let age = defaults.integer(forKey: "age")
let isUseSecure = defaults.bool(forKey: "secure_use")
let g = defaults.double(forKey: "g")
When retrieving objects, the result is optional. This means you can either accept the optionality, or typecast it to a non-optional type and use the nil coalescing operator to handle missing values. For example:
let fruitsArray = defaults.object(forKey: "fruits") as? [String] ?? [String]()
The user defaults are best used for simple pieces of data. If you need to store multiple objects of the same type it’s smarter to use an actual database, like Realm. Database design is an important aspect of the architecture of your app. Good use cases for UserDefaults are:
It’s important to always check whether a data point can, or should be, saved somewhere else. Many back-end frameworks, for instance, already have storage in place to save a current user’s information. The app’s language is saved in the iPhone’s locale settings. One smart way to use user defaults are flags. They are boolean values (true or false) that indicate whether some event or setting has already happened. Examples:
You can also use flags for more complex data points, like dates:
It’s always important to think through the possible scenarios when working with flags, because it’s easy to make mistakes. One way of keeping track is to create a simple flow diagram showing the different flags, states and defaults you’re using in your app. You can then easily spot if your app can get to an unsupported state, and then change your code accordingly.