在 Realm 的本地 JSON 文件上使用 codable

Using codable on local JSON file with Realm

我正在尝试使用 codable 将本地存储的 JSON 对象添加到 Realm,但我不确定我是否做对了。

realm.add(exercise) 不工作,但我不知道哪里出错了。将不胜感激。

这是我的 JSON 数据:

[{
"id":"1",
"name":"Bench Press",
"muscle": "chest",
"information":"Lie on the bench and lower the bar until it reaches your chest and then lift it back up" },{
"id":"2",
"name":"Bicep Curl",
"muscle": "bicep",
"information":"Curl the dumbbell"}]

这是我的对象class:

@objcMembers class StoredExercise: Object, Decodable {
dynamic var id: Int = 0
dynamic var name: String = ""
dynamic var muscle: String = ""
dynamic var information: String = ""

enum CodingKeys: String, CodingKey {
    case id
    case name
    case muscle
    case information
}

required init(from decoder: Decoder) throws {
    
    let container = try decoder.container(keyedBy: CodingKeys.self)
    
    id = try container.decode(Int.self, forKey: .id)
    name = try container.decode(String.self, forKey: .name)
    muscle = try container.decode(String.self, forKey: .muscle)
    information = try container.decode(String.self, forKey: .information)
    
    super.init()
}

override static func primaryKey() -> String? {
    return "id"
}

required override init() {
    super.init()
}

required init(value: Any, schema: RLMSchema) {
    super.init() 
}

required init(realm: RLMRealm, schema: RLMObjectSchema) {
    super.init() 
}

这是我的领域加载代码:

func storeModels() {
guard let url = Bundle.main.url(forResource: "exercises", withExtension: "json") else {
    return
}
do {
    let data = try Data(contentsOf: url)
    guard let exercise = try? JSONDecoder().decode(Exercise.self, from: data) else {
        return
    }
    
    let realm = try Realm()
    print(realm.configuration.fileURL?.absoluteString ?? "")
    
    try realm.write {
        realm.add(exercise)
    }
    
} catch {
    
}

这是一个数组[Exercise].self

guard let exercise = try? JSONDecoder().decode([Exercise].self, from: data) else {
    return
}