Swift coreData - format date and use it in predicate

后端 未结 1 1333
深忆病人
深忆病人 2021-01-26 21:26

H. I have an entity called Agendadate and one called AgendaEvent. AgendaEvent has a many to many relation with AgendaDate (agendaDates).

in my AgendaDate i have an objec

相关标签:
1条回答
  • 2021-01-26 21:38

    Don't use a custom string format for that purpose. You want to fetch all entries which are related to an Agendadate object with a date on the same day as the given day.

    So you compute the start and end of that day first:

    let date = Date()
    
    let cal = Calendar.current
    let startOfDay = cal.startOfDay(for: date)
    let endOfDay = cal.date(byAdding: .day, value: 1, to: startOfDay)!
    

    Then use this SUBQUERY:

    let predicate = NSPredicate(format: "SUBQUERY(agendaDates, $a, $a.dates >= %@ AND $a.dates < %@).@count > 0",
                                startOfDay as NSDate, endOfDay as NSDate)
    

    It tests $a.dates >= startDate AND $a.dates < endDate for all related objects, and yields true if there is at least one matching the condition.

    0 讨论(0)
提交回复
热议问题