NSPredicate 不适用于 long long 值

NSPredicate doesn't work for long long values

我有像这样的简单谓词来从核心数据中获取所有代码对象:

let predicate = NSPredicate(format: "code.state != %@ AND code.validity != %d AND code.validity < %ld", "ACCEPTANCE", 0,  Date().timeIntervalSince1970 * 1000)

现在里面 cellForRow 我正在打印我有的东西:

    print("++++++++++")
    print(product.code)
    print(product.code?.state)
    let a = product.code?.validity ?? 0
    print(a)
    print(Date().timeIntervalSince1970 * 1000)
    print(Double(a) < Date().timeIntervalSince1970 * 1000)

然后我得到以下结果:

code.state != "ACCEPTANCE" AND code.validity != 0 AND code.validity < 4789427390557216924
++++++++++
aaa
Optional("PACKED")
1614253260000
1612447824663.5361
false
++++++++++
product test 5
Optional("PACKED")
1616880420000
1612447824672.909
false
++++++++++
Produkt testowy 1
Optional("UNPACKED")
1611788400000
1612447824678.4438
true
++++++++++
qqq
Optional("UNPACKED")
1612306800000
1612447824702.927
true
++++++++++
test phone 2
Optional("UNPACKED")
1612393200000
1612447824718.4958
true

如您所见,其中两个被打印为错误。那么为什么它们被提取而没有被提取?

问题是谓词中的 %ld 格式与参数类型(Double)不匹配。您有以下选择:

  • %fDouble,
  • %ldInt,
  • %@ 加上 NSNumber,这是最不容易出错的方法。

示例:

NSPredicate(format: "code.validity < %f", Date().timeIntervalSince1970 * 1000)
NSPredicate(format: "code.validity < %ld", Int(Date().timeIntervalSince1970 * 1000))
NSPredicate(format: "code.validity < %@", NSNumber(value: Date().timeIntervalSince1970 * 1000))