Realm版本更新后JSON自动解析到RealmSwift的适配问题求助
Realm 新版本适配方案
快速修复(兼容原有私有API逻辑)
你遇到的第三个报错是因为_rlmCollection返回的是不可变抽象类型RLMCollection,强转为可变的RLMMutableCollection即可调用add方法,修正后代码如下:
case .string: if property.isArray { if let list = object[property.name] as? RealmSwift.RLMSwiftCollectionBase, let arrayInfo = subInfo.array { guard let mutableCollection = list._rlmCollection as? RLMMutableCollection else { return } for str in arrayInfo { mutableCollection.add(str.string! as AnyObject) } } } else { object[property.name] = subInfo.getString() }
长期稳定方案(避免依赖私有API)
直接调用Realm私有API的兼容性极差,版本迭代时随时可能失效,建议改为操作公开API实现,不需要碰内部私有成员:
如果是明确的字符串数组场景,直接转为List<String>操作即可:
case .string: if property.isArray { if let stringList = object[property.name] as? RealmSwift.List<String>, let arrayInfo = subInfo.array { stringList.append(objectsIn: arrayInfo.compactMap(\.string)) } } else { object[property.name] = subInfo.getString() }
如果是泛型解析场景,不确定元素类型,可通过property.objectClassName判断集合元素类型,再做对应转换即可,全程依赖Realm公开接口,后续版本升级不会频繁出现兼容性问题。
内容的提问来源于stack exchange,提问作者RFG
相关产品推荐
相关产品推荐

