使用 NSPredicate 过滤 year/month 的 fetchRequest

Filter fetchRequest for year/month using NSPredicate

我有一个应用程序有多个时间条目,日期保存为 NSDate。

我想使用获取请求来过滤我从其他地方获得的特定年份和月份。如何使用 NSPredicate 过滤年和月?

let predicate = NSPredicate(format: "%K == %D && %K == %D", ???, selectedMonth, ???, selectedYear)

更新

利用 Raki 指出的帮助,我想出了以下代码:

var dateComp = DateComponents()
dateComp.year = Int(selectedYear)
dateComp.month = Int(selectedMonth)
dateComp.day = 1
    
let calendar = Calendar.current
let firstDayOfTheMonth = calendar.date(from: dateComp)
    
var oneMonth = DateComponents()
oneMonth.month = 1
let beginningOfNextMonth = calendar.date(byAdding: oneMonth, to: firstDayOfTheMonth!)

谓词:

let predicate = NSPredicate(format: "date >= %@ AND date < %@", firstDayOfTheMonth as! CVarArg, beginningOfNextMonth as! CVarArg)

我收到带有以下消息的 SIGABRT:

Could not cast value of type 'Foundation.Date' (0x1073a0ae0) to 'Swift.CVarArg' (0x1196851c8).

Xcode 建议我加上 "as!CVarArg"

更新 2

以下谓词现在有效:

let predicate = NSPredicate(format: "%K >= %@ && %K < %@", "date", firstDayOfTheMonth! as NSDate, "date", beginningOfNextMonth! as NSDate)

你不能这样断言,但你可以从你的月份和年份创建两个 Dates,开始日期和结束日期。

现在你需要像这样简单地谓词。

let predicate = NSPredicate(format: "%K >= %@ && %K <= %@", "DateAttribute", startDateOfMonth as NSDate, "DateAttribute", endDateOfMonth as NSDate)

编辑: 如果您不知道如何为 startDateOfMonthendDateOfMonth 创建日期,那么您可以使用 DateComponents.

let selectedMonth = 11
let selectedYear = 2015
var components = DateComponents()
components.month = selectedMonth
components.year = selectedYear
let startDateOfMonth = Calendar.current.date(from: components)

//Now create endDateOfMonth using startDateOfMonth
components.year = 0
components.month = 1
components.day = -1
let endDateOfMonth = Calendar.current.date(byAdding: components, to: startDate!)