gpt4 book ai didi

swift - 使用 LInkingOjbects 的 Realm 在运行时出现 fatal error

转载 作者:行者123 更新时间:2023-11-28 06:30:10 24 4
gpt4 key购买 nike

出现以下 fatal error 。

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"}
}

Category Repository 类:allCategories() 函数中的“let realm =...”行发生 fatal error

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 中的 Object 和 List 属性不是协变的,这意味着它们只能指向指定的类,而不能指向该类的子类。这意味着 GearModel.category 无法链接到 CategoryRepository 对象,但是 CategoryRepository 具有正在尝试继承的 gearList 属性列出链接到它的 GearModel 对象。

在您的特定情况下,尚不清楚为什么 CategoryRepository 继承自 CategoryModel

关于swift - 使用 LInkingOjbects 的 Realm 在运行时出现 fatal error ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40575321/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com