Notice
Recent Posts
Recent Comments
Link
관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] Archive(아카이브), 아카이빙, 언아카이빙, NSCoding 본문

iOS 기본 (swift)

[iOS - swift] Archive(아카이브), 아카이빙, 언아카이빙, NSCoding

jake-kim 2021. 6. 5. 14:45

아카이빙

  • iOS에서 모델 객체를 저장하는 방법 중 하나이며 가장 흔한 방법
  • 객체 아카이브: 객체 그래프를 따라 객체의 데이터 내용을 저장하는 방식
    • 객체 그래프: 객체들의 참조 관계를 나타낸 모습
  • NSCoding 프로토콜 사용: 가변객체나 다중참조 관계를 원래대로 복원해야하는 경우
  • NSCoding 프로토콜의 메서드: 객체 인스턴스를 encoding, edcoding 두 가지 기능

NSCoding 프로토콜

  • 언아카이빙: 아카이브한 데이터로부터 객체를 생성
  • 아카이빙 ex)
    • UIView와 UIVeiwController들은 모두 NSCoding 프로토콜은 conform
    • storyboard같은 interface 파일에 객체를 추가 -> 객체들이 아카이빙 -> 실행 중 객체들이 interface에서 언아카이빙되어 메모리에 로드

아카이빙 구현

  • 아카이빙, 언아카이빙을 위해 객체의 키는 문자열로 구분하며, "forKey:" 부분에서 이용
class Person: NSCoding {
    var name: String = ""
    var age: Int

    func encode(with coder: NSCoder) {
        coder.encode(name, forKey: "name")
        coder.encode(age, forKey: "age")
    }

    required init?(coder: NSCoder) {
        name = coder.decodeObject(forKey: "name") as! String
        age = coder.decodeObject(forKey: "age") as! Int
    }
}
Comments