NSPredicate BETWEEN 两个日期 NSInvalidArgumentException

NSPredicate BETWEEN two dates NSInvalidArgumentException

我想为两个日期创建一个带有 BETWEEN 关键字的 NSPredicate: 我的参数 e_dateDate

类型的 CoreData 实体 属性
let sd = DateComponents(calendar: Calendar.current,year: 2019, month: 1, day: 1).date!
let ed = DateComponents(calendar: Calendar.current,year: 2020, month: 1, day: 1).date!

let whenPredicate = NSPredicate(format: "e_date BETWEEN %@", [sd, ed])

我遇到以下异常:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "e_date BETWEEN %@"'

我尝试将参数转换为 Objective-C 类型,但仍然出现相同的错误。

let whenPredicate = NSPredicate(format: "e_date BETWEEN %@", [sd as NSDate, ed as NSDate])
let whenPredicate = NSPredicate(format: "e_date BETWEEN %@", [sd as NSDate, ed as NSDate] as NSArray)

将 NSPredicate 与 BETWEEN 关键字一起使用的正确方法是什么?

* 已更新 *

我已经完成了 Clean Build Folder错误消失了。

这很奇怪,因为谓词按照你写的方式运行良好:

 let sd = DateComponents(calendar: Calendar.current,year: 2019, month: 1, day: 1).date!
 let ed = DateComponents(calendar: Calendar.current,year: 2020, month: 1, day: 1).date!

 let whenPredicate = NSPredicate(format: "e_date BETWEEN %@", [sd, ed])

 let date = DateComponents(calendar: Calendar.current,year: 2019, month: 10, day: 17).date!

 whenPredicate.evaluate(with: ["e_date": date]) // true

我怀疑是一个错误,你仍然可以使用 <> 并填写反馈。

编辑:这可能是核心数据问题,因为当您使用Objective-C 方法和类型时,语法仍然正确并且有效...

let dates : NSArray = [
    DateComponents(calendar: Calendar.current,year: 2018, month: 10, day: 17).date! as NSDate,
    DateComponents(calendar: Calendar.current,year: 2019, month: 10, day: 17).date! as NSDate,
    DateComponents(calendar: Calendar.current,year: 2020, month: 10, day: 17).date! as NSDate,
]

let whenPredicate2 = NSPredicate(format: "SELF BETWEEN %@", [sd, ed])

dates.filtered(using: whenPredicate2)

EDIT2:我确认 Objective-C 类 您的原始谓词有效...

@objc class MyEntity : NSObject {
    @objc let e_date : NSDate

    init(_ date: NSDate) {
        self.e_date = date

        super.init()
    }
}

let entities : NSArray = [
    MyEntity(DateComponents(calendar: Calendar.current,year: 2018, month: 10, day: 17).date! as NSDate),
    MyEntity(DateComponents(calendar: Calendar.current,year: 2019, month: 10, day: 17).date! as NSDate),
    MyEntity(DateComponents(calendar: Calendar.current,year: 2020, month: 10, day: 17).date! as NSDate),
]

entities.filtered(using: whenPredicate)