使用Codable导入本地JSON到Realm时realm.add方法失效问题求助
问题排查及修复方案
核心错误点
- 类型不匹配:JSON中的
id字段是字符串格式(如"id":"1"),但你的StoredExercise中id定义为Int类型,直接解码会抛出类型不匹配错误,导致解码提前失败。 - 解码类型错误:你的JSON外层是数组结构,同时你自定义的模型类名为
StoredExercise不是Exercise,你当前写的JSONDecoder().decode(Exercise.self, from: data)既用错了类名,也没有适配数组结构,解码会直接返回nil,后续存储逻辑根本不会执行。 - 错误被吞:你用了
try?解码同时catch块为空,所有报错都被隐藏,无法快速定位问题。
修正后代码
模型类解码部分修改
required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) // 先解码String再转Int,适配JSON里的字符串id let idStr = try container.decode(String.self, forKey: .id) guard let idNum = Int(idStr) else { throw DecodingError.dataCorruptedError(forKey: .id, in: container, debugDescription: "id无法转为整数") } id = idNum 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() }
存储逻辑修改
func storeModels() { guard let url = Bundle.main.url(forResource: "exercises", withExtension: "json") else { print("找不到JSON文件") return } do { let data = try Data(contentsOf: url) // 解码为[StoredExercise]数组,用do-catch捕获错误 let exercises = try JSONDecoder().decode([StoredExercise].self, from: data) let realm = try Realm() print(realm.configuration.fileURL?.absoluteString ?? "找不到Realm文件路径") try realm.write { // 如果有重复主键可以用update参数,避免插入失败 realm.add(exercises, update: .modified) } print("存储成功,共\(exercises.count)条数据") } catch { // 打印错误信息方便排查 print("操作失败:\(error.localizedDescription)") } }
额外提示
如果后续插入重复id的数据,add方法的update参数可以指定更新策略,避免主键冲突导致插入失败。
内容的提问来源于stack exchange,提问作者Paolo_Jimenez
相关产品推荐
相关产品推荐

