Saving Data in iOS Part 1

Leela Prasad
Swift India
Published in
4 min readNov 15, 2018

→ User Defaults :

An interface to the user’s defaults database, where you store key-value pairs persistently across launches of your app.

The User Defaults class provides a programmatic interface for interacting with the defaults system. All iOS devices have a database as named defaults to provide the functionality for persistent the app’s related data. This way apps can access the stored values and then perform the logics depend on those.

At runtime, we use User Defaults objects to read the defaults(stored preferences or values) that our app uses from a user’s defaults database. User Defaults caches the information to avoid having to open the user’s defaults database each time we need a default value.

The cache referenced here is an in-memory cache meaning anything stored in User Defaults is loaded into memory on app launch and remains in memory while the app is running. This affects device performance to a greater or lesser degree depending on how much data is stored.

When we set a default value, it’s changed synchronously within our process, and asynchronously to persistent storage and other processes. Simply when we change the value for any stored defaults in run time, it changes its value synchronously from cache. from there it will be saved to disk(data base) asynchronously as these kind of i/o (operations)s are a bit expensive.

→ Storing To Defaults:

The User Defaults class provides the following convenience methods for accessing common types such as floats, doubles, integers, Boolean values, and URLs.

  • func set(_ value: Any?, forKey defaultName: String)
  • func set(_ value: Int, forKey defaultName: String)
  • func set(_ value: Float, forKey defaultName: String)
  • func set(_ value: Double, forKey defaultName: String)
  • func set(_ value: Bool, forKey defaultName: String)
  • func set(_ url: URL?, forKey defaultName: String)

To use an object with user defaults, it must be of Propertylist type or Json type. For example like String, Number, Data, date, array/dictionary. If we want to use our custom objects with userdefaults, we need to covert them into data(object) type.

  • Values returned from UserDefaults are immutable, even if we set a mutable object as the value. For example, if we set a mutable string as the value for “MyStringDefault”, the string we later retrieve using the string(forKey:) method will be immutable.
  • If we set a mutable string as a default value and later mutate the string, the default value won’t reflect the mutated string value unless we call set(_:forKey:) again. for example,

var myCurrentCity = “Sydney”

if we store the above value and later at some point time, retrieving the value with the same key, it returns immutable which means it is ‘let’ constant. we can not change or modify it.

for second example: upon setting the above ‘myCurrentCity’ property in user defaults , later at some point time changing the property(myCurrentCity) value won’t change the value stored in defaults. to change this we need to call one of its methods set(_:forKey:) again.

→ Retrieving From Defaults :

We can use the following methods to retrieve the values we stored in Defaults database.

  • func object(forKey: String) -> Any?

Returns the object associated with the specified key.

  • func url(forKey: String) -> URL?

Returns the URL associated with the specified key.

  • func array(forKey: String) -> [Any]?

Returns the array associated with the specified key.

  • func dictionary(forKey: String) -> [String : Any]?

Returns the dictionary object associated with the specified key.

  • func string(forKey: String) -> String?

Returns the string associated with the specified key.

  • func stringArray(forKey: String) -> [String]?

Returns the array of strings associated with the specified key.

  • func data(forKey: String) -> Data?

Returns the data object associated with the specified key.

  • func bool(forKey: String) -> Bool

Returns the Boolean value associated with the specified key.

  • func integer(forKey: String) -> Int

Returns the integer value associated with the specified key.

  • func float(forKey: String) -> Float

Returns the float value associated with the specified key.

  • func double(forKey: String) -> Double

Returns the double value associated with the specified key.

  • func dictionaryRepresentation() -> [String : Any]

Returns a dictionary that contains a union of all key-value pairs in the domains in the search list.

We know that all retrieving values are immutable types.

→ Responding to Defaults Changes :

You can use key-value observing to be notified of any updates to a particular default value. You can also register as an observer for didChangeNotification on the default NotificationCenter in order to be notified of all updates to a local defaults database.

→ Removing Values From Defaults :

  • func removeObject(forKey: String)

Removes the value of the specified default key.

→ Persisting File References :

it is better to save the file by using bookmarkData(options:includingResourceValuesForKeys:relativeTo:) method on URL, and them persist using set(_:forKey:) method. We can then use the URLByResolvingBookmarkData:options:relativeToURL:bookmarkDataIsStale:error: method to resolve the bookmark data stored in user defaults to a file URL.

→ Let’s see an example :

  • Results:

You can download the sample project here.

— — — — — — — — — *********************** — — — — — — — — —

you can contact / follow me on twitter & linkedIn accounts.

Thanks for reading…

****************************!!!See you!!!****************************

--

--