UserDefaults
An interface to the user’s defaults database, where you store key-value pairs persistently across launches of your app.
사용자의 기본 데이터베이스에 대한 인터페이스로, 앱 실행 전반에 걸쳐 Key-Value 쌍을 지속적으로 저장할 수 있다.
let defaults = UserDefaults.stand
defaults.set("value", forkey: "key")
// 해당 키가 있으면 업데이트, 없으면 추가
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.
let temp = defaults.value(forKey: "key")
print(type(of: temp)) // Optional <Any>
defaults.removeObject(forKey: "key")
struct Person : Codable{
var name : String
var age : Int
}
// 바로 구조체 인스턴스를 바로 넣으면
// defaults.set(sam,forKey: "sam")
// let sam2 = defaults.object(forKey: "sam") as? Person
// print(sam2?.name ?? "")
// 오류
// 사용자 정의 타입 저장하기
if let encodeData = try? JSONEncoder().encode(sam) {
defaults.set(encodeData, forKey: "sam")
}
// 사용자 저장 타입으로 데이터 불러오기
if let data = defaults.data(forKey: "sam") {
if let decodedData = try? JSONDecoder().decode(Person.self, from: data) {
print(decodedData)
}
}
for (key, value) in default.dictionaryRepresentation() {
print("\(key) = \(value) \n")
}