我想用两个关键字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])

我收到以下异常:

由于未捕获的异常而终止应用程序
“NSInvalidArgumentException”,原因:“无法解析格式
字符串“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)

关于ios - NSPredicate在两个日期之间NSInvalidArgumentException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59661190/

10-13 07:44