当尝试对此进行编码时:
class MyClass: Object, Codable {
@Persisted var someValue: String
}
// I've created and added MyClass to Realm. I then query for it and get a `myClassResult` object
let jsonString = try myClassResult.encode(to: JSONEncoder())
我得到这个错误:
Swift.EncodingError.invalidValue(RealmSwift.Persisted<Swift.String>(storage: RealmSwift.(unknown context at $10d2a3778).PropertyStorage<Swift.String>.managed(key: 0)), Swift.EncodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "someValue", intValue: nil)], debugDescription: "Only unmanaged Realm objects can be encoded using automatic Codable synthesis. You must explicitly define encode(to:) on your model class to support managed Realm objects.", underlyingError: nil))
当使用@objc dynamic var
注释时,Realm的早期版本可以进行编码和解码。当我更新代码以使用带有@Persisted
注释的Realmv.10.21.0
时,错误就开始了。
您需要在模型类上实现encode(to:(
class MyClass: Object, Codable {
@Persisted var someValue: String
enum CodingKeys: String, CodingKey {
case someValue
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(someValue, forKey: .someValue)
}
}
// After querying for a `myClassResult` object.
do {
let jsonString = try myClassResult.encode(to: JSONEncoder())
} catch {
print(error)
}