使用LInkingOjbects在Realm运行时发生致命错误
获取以下致命错误。这里使用LInkingOjbects在Realm运行时发生致命错误
fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=1 "Schema validation failed due to the following errors: - Property 'GearModel.category' declared as origin of linking objects property 'CategoryRepository.gearList' links to type 'CategoryModel'" UserInfo={NSLocalizedDescription=Schema validation failed due to the following errors: - Property 'GearModel.category' declared as origin of linking objects property 'CategoryRepository.gearList' links to type 'CategoryModel', Error Code=1}:
对象模型:齿轮模型被分配给一个唯一的类别
import Foundation
import RealmSwift
class GearModel: Object{
dynamic var gearID = NSUUID().uuidString
dynamic var name = ""
dynamic var manufacturer = ""
dynamic var sortOrder = 0
dynamic var category: CategoryModel?
override class func primaryKey() -> String? {return "gearID"}
}
分类型号:试图获得与分配的类别所有GearModel的产品清单。
import Foundation
import RealmSwift
class CategoryModel: Object{
dynamic var categoryID = NSUUID().uuidString
dynamic var sortOrder = 0
dynamic var name = ""
let gearList = LinkingObjects(fromType: GearModel.self, property: "category")
override class func primaryKey() -> String? {return "categoryID"}
}
类别库类:行发生致命错误 “让境界= ....”,在allCategories()FUNC
import Foundation
import RealmSwift
class CategoryRepository: CategoryModel{
class func GetGearItemsForCategory(CategoryID: String) -> Results<GearModel>
{
let realm = try! Realm()
var gearItems = realm.objects(GearModel.self)
let predicate = NSPredicate(format: "categoryID = %@", CategoryID)
gearItems = gearItems.filter(predicate)
return gearItems
}
class func GetCountOfGearItems(CategoryID: String) -> Int
{
let realm = try! Realm()
var gearItems = realm.objects(GearModel.self)
let predicate = NSPredicate(format: "categoryID = %@", CategoryID)
gearItems = gearItems.filter(predicate)
return gearItems.count
}
class func AddCategory(CategoryID: String, Name: String, SortOrder: Int){
let realm = try! Realm()
let category = CategoryModel(name: CategoryID, categoryID: Name, sortOrder: SortOrder)
try! realm.write {
realm.add(category)
}
}
class func allCategories() -> Results<CategoryModel> {
let realm = try! Realm()
return realm.objects(CategoryModel.self).sorted(byProperty: "SortOrder")
}
从具有LinkingObjects
属性的类继承不被支持。
Realm中的对象和列表属性不是协变的,这意味着它们只能指向完全指定的类,而不指向该类的子类。这意味着GearModel.category
无法链接到CategoryRepository
对象,但CategoryRepository
具有继承的gearList
属性,该属性试图列出链接到该对象的对象GearModel
。
在您的具体情况下,不清楚为什么CategoryRepository
继承自CategoryModel
。
老实说,我是Swift的新手,CategoryRepository代码基于Xamarin的教程,然后我将Realm添加为我的数据存储。我今晚会改变这一点,并且标记答案应该如我们所希望的那样运作。 –
错误'Property'GearModel.categories'... '表明您在GearModel中有另一个名为categories的属性。这是哪里? – Michael
良好的捕获,我从错误中复制了一次尝试修复错误的问题与代码不匹配。在上面的代码中修复。我已经把关系从1多变为了许多。那就是为什么类别变成了类别。但是那也行不通。 –
你可以分享'CategoryRepository'类吗? – Dmitry