Reputation: 1018
I try to get an Entity via an NSPredicate from CoreData model. Initially I insert an entity using its id
and now intend to get it. However my code crashes without any further description on specifically my NSPredicate
. I have no idea why? My id
attribute is 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!
Any help most greatly appreciated.
Upvotes: 0
Views: 198
Reputation: 285059
This is a very common mistake.
The placeholder %@
is only for objects, for an Int32
you need %d
or %i
let predicate = NSPredicate(format: "id == %d", id)
And create the fetch request with the concrete NSManagedObject
subclass
let fetchRequest = NSFetchRequest<EmployeeTime>(entityName: "EmployeeTime")
this avoids the type cast later.
Your entire code can be simplified (no optionals needed):
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
However you should avoid try!
. Make your function throw
and hand over a potential error to the caller.
Upvotes: 1