问题
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