本文介绍了制作符合Codable的对象的(深层)副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,该对象从Realm继承了Object,并符合Codable的要求,以便在与API通讯时与JSON相互转换.

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.

如何利用Codable协议进行深拷贝(包括子对象)?

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

推荐答案

这将利用Codable协议对对象进行深层复制.正如@ itai-ferber所提到的,与NSCopying相比,它将有很高的开销.

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
    }

}

这篇关于制作符合Codable的对象的(深层)副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-23 13:18