我有两个实体:
AgendaEvents
AgendaDates
AgendaDates与AgendaEvents有很多关系。
我试图在临时数组(var myTempEvents = [AgendaEvent]())中存储所有在AgendaDates内部的日期(至少)等于定义日期(myDate)的议程事件
myDate是从日历中选择的日期(JTAppleCalendar)。
for date in calendar.selectedDates {
myDate = date
}
现在我需要获得在AgendaDates中至少有一个日期等于myDate的所有AgendaEvent对象。 我需要时间不要影响比较。
我有一个用于此的功能:
func agendaEventsWithDate(date: Date) -> NSFetchRequest<AgendaEvent>
{
// create a fetch request that will retrieve all the AgendaEvents.
let fetchRequest = NSFetchRequest<AgendaEvent>(entityName: "AgendaEvent")
// set the predicate to only keep AgendaEvents where the related AgendaDate's date matches the passed in date.
let cal = Calendar.current
let startOfDay = cal.startOfDay(for: date)print(selectedDate)
let endOfDay = cal.date(byAdding: .day, value: 1, to: startOfDay)!
fetchRequest.predicate = NSPredicate(format: "SUBQUERY(agendaDates, $a, $a.agendaDates >= %@ AND $a.agendaDates < %@).@count > 0", startOfDay as NSDate, endOfDay as NSDate)
return fetchRequest
}
在我的核心数据中,AgendaEvents和AgendaDate之间的关系是agendaDates和AgendaDates有一个对象日期(类型为Date)。
现在我可以执行提取,我将在此功能中执行此操作:
func configuringCell(cell: CalendarAgendaCell, indexPath: IndexPath) {
myTempEvents = try! context.fetch(agendaEventsWithDate(date: selectedDate))
let myEvent = myTempEvent[indexPath.row]
}
此处myTemEvents数组应填充所有在AgendaDates中至少在日期等于myDate的事件。
我现在的问题是: 1)myDate和谓词中的日期有时间组件。 myDate中的时间取决于用户何时选择日期。 AgendaDate中的一个存储在核心数据中。这意味着通常情况永远不会相同,因此myTempEvents将始终为空。+
2)因为第一个问题我无法进行比较。我不知道获取请求是否有效。
谢谢!
更新-------工作副本
func agendaEventsWithDate(date: Date) -> NSFetchRequest<AgendaEvent>
{
// create a fetch request that will retrieve all the AgendaEvents.
let fetchRequest = NSFetchRequest<AgendaEvent>(entityName: "AgendaEvent")
// set the predicate to only keep AgendaEvents where the related AgendaDate's date matches the passed in date.
let cal = Calendar.current
let startOfDay = cal.startOfDay(for: date)
print(selectedDate)
let endOfDay = cal.date(byAdding: .day, value: 1, to: startOfDay)!
fetchRequest.predicate = NSPredicate(format: "SUBQUERY(agendaDates, $a, $a.agendaDates >= %@ AND $a.agendaDates < %@).@count > 0", startOfDay as NSDate, endOfDay as NSDate)
return fetchRequest
}
func configuringCell(cell: CalendarAgendaCell, indexPath: IndexPath) {
let myEvent = myTempEvents[indexPath.row]
cell.configureCell(agendaEvent: myEvent)
}
func calendar(_ calendar: JTAppleCalendarView, didSelectDate date: Date, cell: JTAppleCell?, cellState: CellState) {
selectedDate = date
calendar.reloadData()
myTempEvents = try! context.fetch(agendaEventsWithDate(date: selectedDate))
tableView.reloadData()
}