gpt4 book ai didi

ios - 核心数据 NSPredicate

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

我使用 CoreData 将一个旧项目从 Swift 1 转换为 Swift 4.2(在主要版本步骤中,全部成功构建)。

现在编译器在尝试执行这段代码时会抛出以下错误:

let sortDescriptor = NSSortDescriptor(key: "dateModified", ascending: false)
let predicate = NSPredicate(format: "markAsDeleted == false")
if let itemInspections = item.inspections?.filtered(using: predicate).sortedArray(using: [sortDescriptor]) {
label.text = "Items (\(itemInspections.count))"
}

错误:

2018-09-25 17:19:06.606722+0200 AppName[538:144354] -[_NSFaultingMutableSet filteredOrderedSetUsingPredicate:]: unrecognized selector sent to instance 0x17063afc0 2018-09-25 17:19:06.607861+0200 AppName[538:144354] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_NSFaultingMutableSet filteredOrderedSetUsingPredicate:]: unrecognized selector sent to instance 0x17063afc0'

*** First throw call stack: (0x18f5d6fd8 0x18e038538 0x18f5ddef4 0x18f5daf4c 0x18f4d6d2c 0x100126ce0 0x10015fa10 0x10015fc18 0x195ff9268 0x19575f884 0x19575a4ac 0x1956fc158 0x1928ec274 0x1928e0de8 0x1928e0ca8 0x19285c360 0x1928833c0 0x1956f17a0 0x18f5849a0 0x18f582628 0x18f582a74 0x18f4b2d94 0x190f1c074 0x195764130 0x100110cb4 0x18e4c159c)

libc++abi.dylib: terminating with uncaught exception of type NSException

任何指针将不胜感激。

最佳答案

强烈建议使用适当的谓词和排序描述符重新获取项目,而不是手动

代码假设有一个 NSManagedObject 子类 Inspectionitem 的关系,并且由 item 表示的实体具有唯一属性 名称

let sortDescriptor = NSSortDescriptor(key: "dateModified", ascending: false)
let predicate = NSPredicate(format: "item.name == %@ AND markAsDeleted == FALSE", item.name)
let fetchRequest : NSFetchRequest<Inspection> = Inspection.fetchRequest()
fetchRequest.predicate = predicate
fetchRequest.sortDescriptors = [sortDescriptor]
do {
let itemInspections = try managedObjectContext.fetch(fetchRequest)
label.text = "Items (\(itemInspections.count))"
} catch { print(error) }

如果您只需要筛选项的数量,还有一个更高效的 API

let sortDescriptor = NSSortDescriptor(key: "dateModified", ascending: false)
let predicate = NSPredicate(format: "item.name == %@ AND markAsDeleted == FALSE", item.name)
let fetchRequest : NSFetchRequest<Inspection> = Inspection.fetchRequest()
fetchRequest.predicate = predicate
fetchRequest.sortDescriptors = [sortDescriptor]
do {
let numberOfItemInspections = try managedObjectContext.count(for: fetchRequest)
label.text = "Items (\(numberOfItemInspections))"
} catch { print(error) }

关于ios - 核心数据 NSPredicate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52503233/

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