프로그래밍/iOS
NSCoding, Codable 사용 방법 정리(코드)
turu
2021. 9. 20. 19:50
이렇게 사용하는게 맞는진 모르겠지만, 일단 해결했던 방법을 정리해본다
1. func encode(with:)에서 key값과 함께 encode할때 방법들
클래스 안에 구조체 프로퍼티가 있어서 NSCoding + Codable을 섞는 상황임.
이때 최종 목적은 우선 객체를 Data 로 만들고, 그 Data를 func encode(_ object: Any?, forKey key: String) 함수를 사용하여 키 값과 함께 encode 하는 것이다.
방법1: JSONEncoder, JSONDecoder를 사용
func encode(with aCoder: NSCoder) {
print(#function, #line)
aCoder.encode(name, forKey: "name")
aCoder.encode(age, forKey: "age")
let jsonEncoder = JSONEncoder()
let cityData = try! jsonEncoder.encode(city) // -> JSONEncoder를 사용하여 Data로 변환함
aCoder.encode(cityData, forKey: "city")
aCoder.encode(imageData, forKey: "imageData")
}
required init?(coder aDecoder: NSCoder) {
name = aDecoder.decodeObject(forKey: "name") as! String
age = aDecoder.decodeInteger(forKey: "age")
do {
let jsonDecoder = JSONDecoder()
let cityData = aDecoder.decodeObject(forKey: "city") as! Data // -> Data로 바꾸고
self.city = try jsonDecoder.decode(City.self, from: cityData) // JSONDecoder를 사용하여 Data->City로 변환
} catch {
self.city = City(name: "error", num: 10)
}
imageData = aDecoder.decodeObject(forKey: "imageData") as! Data
}
GitHub - jogiking/MultiSceneWithUserDefaultTest
Contribute to jogiking/MultiSceneWithUserDefaultTest development by creating an account on GitHub.
github.com
방법2: PropertyListEncoder, PropertyListDecoder를 사용
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "name") // String
aCoder.encode(age, forKey: "age") // Int
do {
let cityData = try PropertyListEncoder.init().encode(city) // -> 이 부분!
aCoder.encode(cityData, forKey: "city") // City 구조체
} catch {
print(#function, #line)
}
aCoder.encode(imageData, forKey: "imageData") // Data
}
required init?(coder aDecoder: NSCoder) {
print(#function, #line)
name = aDecoder.decodeObject(forKey: "name") as! String
age = aDecoder.decodeInteger(forKey: "age")
let cityData = aDecoder.decodeObject(forKey: "city") as! Data
city = try! PropertyListDecoder.init().decode(City.self, from: cityData) // -> 이 부분!
imageData = aDecoder.decodeObject(forKey: "imageData") as! Data
}
GitHub - jogiking/MultiSceneWithUserDefaultTest
Contribute to jogiking/MultiSceneWithUserDefaultTest development by creating an account on GitHub.
github.com
반응형