gpt4 book ai didi

ios - 使用NSPredicate过滤年/月的fetchRequest

转载 作者:行者123 更新时间:2023-12-01 16:02:44 28 4
gpt4 key购买 nike

我有一个应用程序,其中包含多个时间条目,并且日期保存为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!)

关于ios - 使用NSPredicate过滤年/月的fetchRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42386771/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com