NSPredicate crash after swift 3 migration

2019-09-13 05:47发布

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条回答
男人必须洒脱
2楼-- · 2019-09-13 06:28

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.

查看更多
登录 后发表回答