NSPredicate crash after swift 3 migration

筅森魡賤 提交于 2019-12-12 03:48:26

问题


after migration to swift3, I have an issue that cannot fix

    let fetchRequest: NSFetchRequest<User> = User.fetchRequest()
    fetchRequest.predicate = NSPredicate(format: "id == %@", id)

my App crashes on second line, bad access, no reason. types are right, no log, nothing, just bad access. any suggestions?

Found a reason, predicate is wrong, cause id is Int64 type, have no idea what kind of predicate I need for this version of swift


回答1:


The %@ format expect a Foundation object as argument, compare "Predicate Format String Syntax" in the "Predicate Programming Guide".

You can bridge the Int64 to NSNumber:

let id = Int64.max
let predicate = NSPredicate(format: "id == %@", id as NSNumber)
print(predicate) // id == 9223372036854775807

or change the format to "long long":

let id = Int64.max
let predicate = NSPredicate(format: "id == %lld", id)
print(predicate) // id == 9223372036854775807

Bridging all number types to NSNumber is possible as of Swift 3.0.1 (Xcode 8.1) with the implementation of SE-0139 Bridge Numeric Types to NSNumber and Cocoa Structs to NSValue.



来源:https://stackoverflow.com/questions/40686005/nspredicate-crash-after-swift-3-migration

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