Make a (deep) copy of an Object that conforms to Codable

匆匆过客 提交于 2019-12-11 06:17:56

问题


I have an object that subclasses Object from Realm, and conforms to Codable in order to convert to and from JSON when talking to an API.

How can I make a deep copy (include children objects) by leveraging the Codable protocol?


回答1:


This will make a deep copy of an object leveraging the Codable protocol. As mentioned by @itai-ferber it will have a high overhead when compared to NSCopying.

class MyObject: Object, Codable {

    /* details omitted */
    var children = List<ChildObject>()

    func copy() throws -> MyObject {
        let data = try JSONEncoder().encode(self)
        let copy = try JSONDecoder().decode(MyObject.self, from: data)
        return copy
    }

}


来源:https://stackoverflow.com/questions/46900984/make-a-deep-copy-of-an-object-that-conforms-to-codable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!