0

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.

Mohsin Khubaib Ahmed
  • 1,008
  • 16
  • 32
  • Possible duplicate of [EXC\_BAD\_ACCESS when building nspredicate](https://stackoverflow.com/questions/23610509/exc-bad-access-when-building-nspredicate) – Larme Nov 16 '18 at 09:04

1 Answers1

1

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.

vadian
  • 274,689
  • 30
  • 353
  • 361