我有两个实体:
AgendaEvents
AgendaDates
AgendaDates与AgendaEvents有一对多的关系。
我试图存储在一个临时数组中(var myTempEvents = [AgendaEvent]()) 所有在AgendaDates内部的AgendaEvent日期等于定义的日期(让myDate = Date())
到目前为止,我有这个:
var myEventDate = [String]()
var myTempEvents = [AgendaEvent]()
var myEvents = [AgendaEvent]()
var myDate = Date()
func getEventDates() {
for event in myEvents {
for date in (event.agendaDates as? Set<AgendaDate>)! {
let eventDates = date.agendaDates
eventDate = eventDates
formatter.dateFormat = "dd MM yyyy"
let eventDateString = formatter.string(from: eventDate)
myEventDate.append(eventDateString)
}
}
}
我现在需要做的是检查一个AgendaEvents是否有一个等于myDate的日期,如果是的话,我需要将该事件添加到myTempEvents。
这应该发生在这个函数中:
func configureCell(cell: CalendarAgendaCell, indexPath: IndexPath) {
for dates in calendar.selectedDates {
for dateOfEvent in myEventDate {
formatter.dateFormat = "dd MM yyyy"
let dateToCompare = formatter.string(from: dates)
if dateOfEvent == dateToCompare {
let myEvent = myTempEvents[indexPath.row]
cell.configureCell(agendaEvent: myEvent)
} else {
//empty the tempArray
}
}
}
}
此函数由tableView的cellForRowAt函数调用:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Dequeue Cell
let cell = tableView.dequeueReusableCell(withIdentifier: "AgendaCell", for: indexPath) as! AgendaCell
//Fetch model object to display
configureCell(cell: cell, indexPath: indexPath)
return cell
}
我不擅长核心数据(仍在学习),所以任何帮助都会非常感激。
谢谢!
UPDATE --------- 14/09/17
正如@Simo建议我编辑我的代码一样:
func agendaEventsWithDate(date: Date) -> NSFetchRequest<NSFetchRequestResult>
{
// create a fetch request that will retrieve all the AgendaEvents.
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "AgendaEvent")
// set the predicate to only keep AgendaEvents where the related AgendaDate's date matches the passed in date.
fetchRequest.predicate = NSPredicate(format: "ANY agendaDates.agendaDates == %@", date as CVarArg)
return fetchRequest
}
let myTempEvents = try?context.fetch(agendaEventsWithDate(date: Date()))
上下文是:
let ad = UIApplication.shared.delegate as! AppDelegate
let context = ad.persistentContainer.viewContext
但是我收到此错误:
模糊地使用&#39; fetch&#39;
谢谢!
答案 0 :(得分:0)
有一种更简单的方法可以实现这一点而无需自己进行比较。您应该阅读NSFetchRequest
使用谓词。
您可以获取存储在核心数据中的所有AgendaEvent
,然后对其进行过滤,这样您只剩下包含与您指定日期匹配的AgendaDate
的事件。
获取请求(包含在一个很好的提供者函数中)可能看起来像:
func agendaEventsWithDate(date: Date) -> NSFetchRequest
{
// create a fetch request that will retrieve all the AgendaEvents.
let fetchRequest = NSFetchRequest(entityName: "AgendaEvent")
// set the predicate to only keep AgendaEvents where the related AgendaDate's date matches the passed in date.
fetchRequest.predicate = NSPredicate(format: "ANY agendaDates.date == %@", date)
return fetchRequest
}
这显然假定您的AgendaEvent
实体与AgendaDate
的关系称为agendaDates
,并且您的AgendaDate
实体还有一个名为date
的属性。
然后,当您执行获取请求时,您将返回一个您正在寻找的项目数组。不需要进行所有手动比较。
let myTempEvents = try? managedObjectContext?.executeFetchRequest(self.agendaEventsWithDate(someDate))