我尝试通过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!
非常感谢任何帮助。
答案 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
并将潜在的错误移交给调用者。