我有一个嵌套的对象列表,我试图将其添加到Realm实例中,但是它不起作用。我简化了下面的对象以帮助理解问题。
使用的解码方法在父级有效,而在子级无效。
class: myObject: Object, Codable {
@objc dynamic var id: Int64 = 0
@objc dynamic var name: String?
let objects = List<myObject>()
}
... coding keys, decode, encode, realm required inits
解码方法
static func decodeResponse<T:Codable>(_ response : Any?) -> T? {
if let response = response, let dict = response as? [String:Any] {
var dictionaryToParse = dict
var arrayToParse: [[String:Any]]?
if let dataObject = dict["data"] as? [String:Any] {
//sometimes the response has an outer "data" OBJECT
dictionaryToParse = dataObject
} else if let dataArray = dict["data"] as? [[String:Any]] {
//sometimes the response has an outer "data" ARRAY
arrayToParse = dataArray
}
do {
guard let data = try? JSONSerialization.data(withJSONObject: arrayToParse ?? dictionaryToParse, options: []) else { return nil }
let obj = try JSONDecoder().decode(T.self, from: data)
return obj
}
catch let error {
print("ERROR: (decodeResponse): \(error)")
return nil
}
}
return nil
}
问题。解码适用于顶级myObject
,但不适用于let objects = List<myObject>()
。