기어가더라도 제대로
[SwiftUI-기초] Codable (with UserDefaults) 본문
- AppStorage 같은 경우엔 간단한 String, Int, Bool 등을 저장가능
- 복잡한 데이터 타입을 담기위해선 UserDefault 자체를 씀
struct User: Codable {
let firstName: String
let lastName: String
}
Codable 이라는 프로토콜을 채택하는데, 이것은 이런 의미를 가지고 잇다.
- 이런 인스턴스를 archiving 하기 -> Encode()
- unarchiving 해서 인스턴스화 하기 -> Decode()
- 즉, Codable == Encodable + Decodable
- 어쨌든 저장하기 위해서는 plane 한 Text 로 저장이 가능한데 인스턴스의 경우 plane 한 텍스트로 만드는 것을 Encode,
- Text 에서 인스턴스화 하는 것을 Decode 라고 한다.
- 여러 포맷이 있는데 일반적으로 많이 사용되는 text의 포맷인 JSON 을 사용할 것이다.
@State private var user = User(firstName: "Taylor", lastName: "Swift")
...
Button("Save User") {
let encoder = JSONEncoder()
if let data = try? encoder.encode(user) {
UserDefaults.standard.set(data, forKey: "UserData")
}
}
참조
https://www.hackingwithswift.com/books/ios-swiftui/archiving-swift-objects-with-codable
Archiving Swift objects with Codable - a free Hacking with iOS: SwiftUI Edition tutorial
Was this page useful? Let us know! 1 2 3 4 5
www.hackingwithswift.com
2022.11.05 - [SwiftUI - 기초] - [SwiftUI-기초] AppStorage - UserDefault 를 사용
'SwiftUI - 기초' 카테고리의 다른 글
[SwiftUI-기초] ScrollView, Stack, Lazy Stack (0) | 2022.11.08 |
---|---|
[SwiftUI-기초] image, resizing, Geometry Reader(feat. 중앙정렬) (1) | 2022.11.07 |
[SwiftUI-기초] AppStorage - UserDefault 를 사용 (0) | 2022.11.05 |
[SwiftUI-기초] onDelete() - List의 row 삭제하기(Array item delete) (0) | 2022.11.04 |
[SwiftUI-기초] Custom Color, dark mode (0) | 2022.11.04 |
Comments