It was suggested that this thread is an exact duplicate of my question however, my app wasn't crashing and I'm not migrating to Swift 3. It just wasn't returning any results. So the solution is essentially the same but the behavior on which my question is based is quite different.
After reading many threads this morning I'm pretty confident this code is correct and should work:
func fetchUnits(weightUnitUid: Int? = nil) -> [WeightUnit] {
let fetchRequest = NSFetchRequest(entityName: "WeightUnit")
if let weightUnitFilter = weightUnitUid {
let filterPredicate = NSPredicate(format: "uid = %@", weightUnitFilter)
fetchRequest.predicate = filterPredicate
}
but here's what it looks like in the debugging console:
(lldb) po filterPredicate // uid == nil
I'm passing in 0 and weightUnitUid
is in fact 0 at this point so I'd expect:
uid == 0
I know %@
should be able to handle an NSNumber and that's what I need. Where I'm going wrong.
Thanks
The %@
format expects a Foundation object as argument, the zero
is interpreted as nil
.
You can convert the integer to NSNumber
:
let filterPredicate = NSPredicate(format: "uid = %@", weightUnitFilter as NSNumber)
or use the "long int" format instead:
let filterPredicate = NSPredicate(format: "uid = %ld", weightUnitFilter)