我可以基于子类对象的属性创建谓词吗?

时间:2019-01-24 05:37:59

标签: swift core-data nspredicate nsfetchedresultscontroller

我有两节课:活动和动作。活动是父类,动作是孩子,这是一对多的关系。在设置NSFetchedResultsController时,我想基于子类的属性设置一个谓词。这是一个例子...

PHP

如果我要使用for in循环过滤活动,那将是这样...

fetchRequest.predicate = NSPredicate(format: "filter only activities that have actions which have their date property equalling today")

2 个答案:

答案 0 :(得分:1)

您可以在SUBQUERY中使用NSPredicate。在这里,我以NSArray为例。

let today = Date()

let array: NSArray = [
    Activity(actions: [
        Action(date: today)
        ]),
    Activity(actions: [
        Action(date: Date(timeIntervalSince1970: 0))
        ])
]

// here is your predicate
let result = array.filtered(using: NSPredicate(format: "SUBQUERY(actions, $action, $action.date == %@) .@count > 0", today as CVarArg))
print(result.count) // 1

请注意,我在这里使用==来比较日期,这意味着只有在日期完全等于today的情况下,它才会匹配。如果“今天”是指“ 24小时内的任何时间”,那么您将不得不使用this question中建议的答案:

func getLastAndNextMidnight(date: Date) -> (Date, Date) {
    let dateComponents = Calendar.current.dateComponents([.year, .month, .day], from: date)
    var oneDay = DateComponents()
    oneDay.day = 1
    let lastMidnight = Calendar.current.date(from: dateComponents)!
    let nextMidnight = Calendar.current.date(byAdding: oneDay, to: lastMidnight)!
    return (lastMidnight, nextMidnight)
}
let midnights = getLastAndNextMidnight(date: today)
let result = array.filtered(using: NSPredicate(format: "SUBQUERY(actions, $action, ($action.date >= %@) AND ($action.date <= %@)) .@count > 0", midnights.0 as CVarArg, midnights.1 as CVarArg))
print(result.count)

答案 1 :(得分:1)

今天有采取任何行动吗?谓词格式:

"ANY actions.date == today"