我正在一个涉及 Realm
和使用泛型的iOS项目中工作 . 我正在探索克隆检索到的 Realm
对象的方法,以便在写入事务之外更新它,然后使用泛型将其发送到更新函数 .
我面临一个奇怪的问题,我不知道它是否与 Realm
或泛型的东西有关 . 您将获得帮助
设置:一个继承自 Realm
Object
的类 GenericObject
,以及一个名为 Sale
的子类:
GenericObject: Object
Sale: Generic Object // This class includes a primary key called "id"
我从网上获取一个 Sale
对象,我可以将它保存在 Realm
中,在写入事务之外创建一个新对象(我可以保存它而不用担心写入事务,但我想使用相同的代码和流程更新)
当我修改对象的属性并尝试更新Realm时,它会抛出异常,因为无法找到主键 . (primaryKey在子类 Sale
中定义)
我已经能够在 Sale
中找到我的 newItem()
方法的问题,如下所示:
override func newItem<T:GenericObject>(ofType itemType: T.Type) -> T {
let dictionary = self.getDictionary()
let newItem = T.init()
newItem.updateWithDictionary(dict: dictionary)
print("Type: \(type(of: newItem)) - Object: \(newItem)")
return newItem
}
然后,我将其称为如下:
let newObject = object.newItem(ofType: Sale.self)
self.realm.add(newObject, update: true)
到现在为止还挺好 . 我从网上检索对象,它的工作原理 . print()
报告 type(of:)
实例化对象是 Sale
,对象的打印输出也说 Sale
Type: Sale - Object: Sale { ....
当我更新对象并保存它时,它无法说 Realm
找不到主键, type(of:)
报告 Sale
,但实例打印为 GenericObject
超类,如下所示:
Type: Sale - Object: GenericObject { ....
此结果运行相同的代码和相同的代码执行 . 我正在使用Xcode 10和Swift 4.2,与Realm 3有什么想法可能会发生在这里?