본문 바로가기
iOS

Relationship을 가지는 CoreData를 json으로 변환하기

by vapor3965 2021. 9. 7.

목차

     

    우선 다음과 같은 Entity 2개가 있고, 

    각 relationship을 갖고 있다라고 가정하자.  

    그래서 Human에 대한 데이터를 json으로 저장하고자 한다.

     

    각 NSManagedObject를 extension하여 encdoable을 채택해준다. 

     

    extension Human: Encodable{
        enum CodingKeys: String, CodingKey {
            case name, age
        }
        public func encode(to encoder: Encoder) throws {
            var container = encoder.container(keyedBy: CodingKeys.self)
            try container.encode(name, forKey: .name)
            try container.encode(age, forKey: .age)
        }
    }
    
    extension Ages: Encodable {
        enum CodingKeys: String, CodingKey {
            case age, birth, // human
        }
        public func encode(to encoder: Encoder) throws {
            var container = encoder.container(keyedBy: CodingKeys.self)
            try container.encode(age, forKey: .age)
            try container.encode(birth, forKey: .birth)
            // try container.encode(human, forKey: .human)
        }
    }

     

    Human을 Json으로 인코딩하면 되는데,  

    let json = try JSONEncoder().encode(model)

    여기서 주의할점이, 

    relationship이 둘다 적용되어있으므로, 한쪽에만 encode를 추가해야한다. 

    즉 위의 코드를 보면 일부로 human은 주석처리했다. 

    만약 주석처리 하지 않으면, json으로 인코딩할 때 계속 무한루프가 걸려서 다음과 같은 에러가 발생한다. 

     

     

    그러므로, Human을 뽑고자 하므로, Human에만 releationship을 인코딩 코드를 추가해주고,

    Ages에는 releationship을 인코딩 코드를 추가하지 않도록 한다. 

     

    그럼 정상적으로, 다음과 같이 뽑을 수 있다.

    {"name":"10CE7E5E-1C3A-4D44-B0A6-00AEE6F33BF5","age":{"age":51,"birth":73}}

     

     

     

     

    댓글