🍎 Apple/iOS

[iOS] struct도 encoding을 해야한다.

PushedGun 2023. 10. 1. 19:29

1. 문제 상황

1-1) shape 객체를 아카이빙하려고 하였다.

class Shape : NSObject, NSCoding {

    private var identifier : String

    private var point : Point

    private var size : Size

}

 

1-2) 그런데 encode이 매번 실패하였다. 디버거로 확인해보니, 내가 만든 struct 타입에서 encode를 실패하는 것을 확인할 수 있었다.

    func encode(with aCoder: NSCoder) {

        aCoder.encode(identifier, forKey: "identifier")

        aCoder.encode(point, forKey: "point") // 실패

        aCoder.encode(size, forKey: "size") // 실패

}

 

2. 결론

class 객체는 주소가 아닌 값을 저장하기 위해 NSCoding 프로토컬을 상속받는 것으로 알고 있다.

그래서인지 Struct 객체는 값 객체라 막연히 따로 코드를 작성하지 않아도 괜찮을 줄 알았다..

 

‼️ struct는 Codable 프로토컬을 상속받아 encoding, decoding을 사용할 수 있다.

 

Tip. 

Codable 프로토컬을 사용하면 encoding과 decoding 모두 되지만,

encoding만 필요한 경우 Encodable, decoding만 필요한 경우 Decodable 프로토컬을 사용하면 더욱 좋은 코드가 된다.