iOS & Swift 공부 - User Defaults

김영채 (Kevin)·2021년 3월 15일
0

iOS & Swift

목록 보기
90/107
post-thumbnail
let defaults = UserDefaults.standard

defaults.set(0.24, forKey: "Volume")
defaults.set(true, forKey: "MusicOn")
defaults.set("Angela", forKey: "Name")
defaults.set(Date(), forKey: "AppLastOpenedByUser")

let array = [1,2,3]
defaults.set(array, forKey: "array")

let volume = defaults.float(forKey: "Volume)
let appLastOpened = defaults.object(forKey: "AppLastOpenedByUser")

let myArray = defaults.array(forKey: "array") as! [Int]
// You would have to typecast it as Swift does not know what the data 
// type is by default

let dictionary = ["name", "Angela"]
defaults.set(dictionary, "forKey: "dict")

let myDict = defaults.dictionary(forKey: "dict")
  • It's a good idea to keep a Constants.swift file to store the key strings

  • Your app would crash if the String is wrong

  • You should only really be using UserDefaults to persist small bits of data.

    ex. Boolean, Name, etc

→ Once you try to store arrays or any big types of data, it can easily become unmanageable.

→ User Defaults is not a database and it should not be used as a DB.

Why?

Because the key-value pairs of User Defaults are saved into a "plist", and that entire plist of your UserDefault has to be loaded up synchronously. So, all of it gets loaded up before you can access any of the values contained inside the keys.

ex. Even if you would want to load up the Double value for the volume (i.e 4.5), which is a very small piece of data, your iPhone would have to load up the entire plist before accessing such volume data.

profile
맛있는 iOS 프로그래밍

0개의 댓글