在将Core Data与SwiftUI结合使用时,我的以下代码编译没有问题:
@FetchRequest(
entity: MyEntity.entity(),
sortDescriptors: [NSSortDescriptor(keyPath: \MyEntity.name, ascending: true)]
) var myList: FetchedResults<MyEntity>
......
func wonderFunctio() {
let theName = "Donald-Duck"
print(#function)
......
print("myList = \(myList.count)")
let predic = NSPredicate(format: "name == %@", theName)
if FetchRequest<NSFetchRequestResult>(entity: MyEntity.entity(),
sortDescriptors: [],
predicate: predic)
.wrappedValue.count != 0 {
print("Useful message ....")
}
不幸的是,运行时出现问题。我在 if FetchRequest 行中收到此错误。
Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1eceee678)
我的代码中是否有任何不合适的内容?
答案 0 :(得分:1)
FetchRequest<NSFetchRequestResult>(entity...
是一个属性包装器,因此我认为它是无效的用法。
这里是直接使用CoreData NSFetchRequest
的可能解决方案,这似乎是在函数中使用的更合适的方式
let theName = "Donald-Duck"
let request: NSFetchRequest<MyEntity> = MyEntity.fetchRequest()
request.predicate = NSPredicate(format: "name == %@", theName)
if let result = try? self.context.count(for: request), result != 0 {
// .. do anything needed
}