Why is this predicate format being turned into '= nil'

≡放荡痞女 提交于 2019-12-24 05:02:37

问题


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


回答1:


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)


来源:https://stackoverflow.com/questions/41066919/why-is-this-predicate-format-being-turned-into-nil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!