iosswiftcore-datapredicates

Count query Core Data predicate


i have a entity called schedule that has many alarms (other entity), i want to get only schedules that have less then 30 future alarms. Searching all around i get that query that not works /:

 let predicateFutureAlarms = NSPredicate(format: "(alarms.date > %@).@count < 30", NSDate().timeIntervalSince1970)

(on running time a (lldb) appears on console and appoints to the initialization of that variable)


Solution

  • There are at least two problems:

    I cannot test it currently, but something like this should work:

    let now = NSDate()
    let predicate = NSPredicate(format: "SUBQUERY(alarms, $a, $a.date > %@).@count < 30", now)
    

    For each Schedule object, the SUBQUERY(...) evaluates to all related alarms objects which have a date which is greater than now.

    See "Predicate Format String Syntax" for a general description of the predicate syntax. The "SUBQUERY" expression is poorly documented, compare the NSExpression class reference or Quick Explanation of SUBQUERY in NSPredicate Expression.