NSPredicate |给实体获取请求提供严重异常斯威夫特4

时间:2018-11-16 05:39:50

标签: swift core-data nspredicate

我尝试通过NSPredicate从CoreData模型获取一个实体。最初,我使用实体的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!

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

这是一个非常常见的错误。

占位符%@仅适用于对象,对于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并将潜在的错误移交给调用者。