问题描述
迁移到swift3后,我遇到一个无法解决的问题
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?
找到原因,谓词错误,原因是ID为Int64类型,不知道此版本的swift我需要哪种谓词
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
推荐答案
%@
格式期望以 Foundation对象作为参数,进行比较
在谓词编程指南中。
The %@
format expect a Foundation object as argument, compare"Predicate Format String Syntax" in the "Predicate Programming Guide".
您可以将 Int64
桥接到 NSNumber
:
let id = Int64.max
let predicate = NSPredicate(format: "id == %@", id as NSNumber)
print(predicate) // id == 9223372036854775807
或将格式更改为 long long:
or change the format to "long long":
let id = Int64.max
let predicate = NSPredicate(format: "id == %lld", id)
print(predicate) // id == 9223372036854775807
从Swift 3.0.1(Xcode 8.1)开始,通过实现
。
Bridging all number types to NSNumber
is possible as of Swift 3.0.1 (Xcode 8.1) with the implementation ofSE-0139 Bridge Numeric Types to NSNumber and Cocoa Structs to NSValue.
这篇关于迅速迁移3后NSPredicate崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!