NSPredicate |在 Entity Fetch Request 上给出错误的异常 | Swift 4

NSPredicate | Gives bad exception on Entity Fetch Request | Swift 4

我尝试通过 CoreData 模型的 NSPredicate 获取实体。最初我使用其 id 插入一个实体,现在打算获取它。然而,我的代码崩溃了,没有任何关于我的 NSPredicate 的进一步描述。我不知道为什么?我的 id 属性是 Int32:

        var employTime:EmployeeTime?
        let context = getContext()
        let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "EmployeeTime")

        //code crashes on this bottom line
        let predicate = NSPredicate(format: "id == %@", id)
        fetchRequest.predicate = predicate
        let employTimes = try! context.fetch(fetchRequest) as? [EmployeeTime]
        if (employTimes?.count)! > 0 {
            for et in employTimes! {
                if et.id == id {
                    employTime = et
                }
            }
        } else {
            employTime = EmployeeTime(context: context)
        }
        return employTime!

非常感谢任何帮助。

这是一个很常见的错误。

占位符%@仅用于对象,对于Int32你需要%d%i

let predicate = NSPredicate(format: "id == %d", id)

并使用具体的 NSManagedObject 子类

创建获取请求
let fetchRequest = NSFetchRequest<EmployeeTime>(entityName: "EmployeeTime")

这避免了以后的类型转换。


你的整个代码可以被简化(不需要选项):

let employTime:EmployeeTime
let context = getContext()
let fetchRequest = NSFetchRequest<EmployeeTime>(entityName: "EmployeeTime")
let predicate = NSPredicate(format: "id == %d", id)
fetchRequest.predicate = predicate
let employTimes = try! context.fetch(fetchRequest)
if let et = employTimes.first {
   employTime = et
} else {
   employTime = EmployeeTime(context: context)
}
return employTime

但是您应该避免 try!。使您的函数 throw 并将潜在的错误移交给调用者。