`RLMArray` 不符合协议 'Encodable'

`RLMArray` does not conform to protocol 'Encodable'

我想做:

问题:

错误信息:

代码:

public class Hobby: Object, Codable {
    @objc dynamic var  title: String?
    @objc dynamic var  category: String?
}
public class Person: Object, Codable { // Error: Type 'Person' does not conform to protocol 'Encodable'
    @objc dynamic var  name: String?
    @objc dynamic var  hobbies: RLMArray<Hobby>?

    required convenience public init(from decoder: Decoder) throws {
        self.init()
        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try container.decode(String.self, forKey: .name)
        hobbies = try container.decode(RLMArray<Hobby>?.self, forKey: .hobbies)
    }
}
func sample() {
    let person = try? JSONDecoder().decode(Person.self, from: "{\"name\" : \"aaa\",\"hobbies\" : [{\"title\" : \"fishing\",\"category\" : \"outdoor\"},{\"title\" : \"reading\",\"type\" : \"indoor\"}]}".data(using: .utf8)!)
    print(person)
    let realm = try! Realm()
    try! realm.write {
        realm.add(person!)
    }
}

你有什么想法吗?

斯威夫特4 领域斯威夫特

Codable 与 Decodable + Encodable 完全相同。如果你想符合 Codable 你需要实现编码函数,对于你的 Person 对象来说是:

enum CodingKeys: String, CodingKey {
        case name
        case hobbies
// or: case hobbies = "customHobbiesKey" if you want to encode to a different key
}

func encode(to encoder: Encoder) throws {
    do {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(name, forKey: .name)
        try container.encode(hobbies, forKey: .hobbies)
    } catch {
        print(error)
    }
}

将此添加到您的个人 class,然后为您的爱好实施同样的事情 class。

因为我不确定你是否想要编码:如果你需要做的只是从 Json 创建 Realm-Objects 我会简单地将 'Codable' 替换为'Decodable'-协议。

编辑:我注意到问题与 RLMArray 有关。我不确定 codable 如何与 RLMArray 一起使用,但如果它不起作用,您可以尝试将声明替换为

let hobbies = List<Hobby>()

然后在 init() 中将 'hobbies' 行替换为:

let tempHobbyList: [Hobby] = try container.decode([Hobby].self, forKey: .hobbies)
self.hobbies.append(objectsIn: tempHobbyList)

这就是我如何使用 realmObjects 获得我的列表以与 codable 一起工作