我正在构建一个费用管理器,并且我有一个带有过滤器的搜索 功能。对于每个选定的过滤器,我将相应的谓词附加到 fetchedResultsController 的谓词数组中。在我的过滤器中,我有“预算”和“费用”选项。以下代码显示了我如何附加谓词。
if filterCell[0][0] {
predicatesArray.append(NSPredicate(format: "type == %@", "budget" as NSString))
}
if filterCell[0][1] {
predicatesArray.append(NSPredicate(format: "type == %@", "expense" as NSString))
}
回到主 TableView ,我得到了这行代码:
fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicatesArray)
当只选择一个预算或费用时,这工作得很好,当它们都被选择时,tableview 是空的(很明显,type 不能同时是“budget"和 "expense"),所以我切换到 orPredicateWithSubpredicates
。现在,如果我在我的过滤器中选择“预算”并按确定,我仍然会得到费用条目,反之亦然,因为此 View Controller 包含一个默认谓词(用户在选择一段时间后进入此 View 日期,例如 13.11 - 16.11)并使用 orPredicateWithSubpredicates
什么都不做,因为我的日期谓词将始终为真,唯一的选择是 andPredicateWithSubpredicates
我应该在我的代码中修改什么才能使其正常工作?
最佳答案
我解决了。问题是在设置谓词时不应用它们。正确的方法是 andPredicateWithSubpredicates
而我应用谓词的方式是使用以下代码:
if filterCell[0][0] && filterCell[0][1] {
predicatesArray.append(NSPredicate(format: "(type == %@) OR (type == %@)", "budget" as NSString, "expense" as NSString))
} else if filterCell[0][0] {
predicatesArray.append(NSPredicate(format: "type == %@", "budget" as NSString))
} else if filterCell[0][1] {
predicatesArray.append(NSPredicate(format: "type == %@", "expense" as NSString))
}
关于ios - NSCompoundPredicate 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47336074/