ios - NSCompoundPredicate 无法正常工作

标签 ios swift nspredicate nsfetchedresultscontroller

我正在构建一个费用管理器,并且我有一个带有过滤器的搜索 功能。对于每个选定的过滤器,我将相应的谓词附加到 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/

相关文章:

ios - 如何从 Swift 的核心数据中删除特定的实体数据?

ios - 从 'String' 转换为不相关类型 'LocationModel' 始终失败警告

ios - 如何使用倒数计时器停止游戏 - iOS [SWIFT] -

ios - NSManagedObjectContext.fetch 不一致(_ :) method documentation

ios - 损坏的应用程序,UIViewcontroller EXC_BAD_ACCESS 在 vi​​ewWillAppear 之后

ios - 应用程序创建了 Stripe 客户,但由于 "no such customer"而无法获取临时 key

ios - Swift:在协议(protocol)中使用未定义的函数?

swift - 多个 UITextFields 和 textDidChangeNotification 通知

ios - NSPredicate 搜索具有 nil 值的连接表

core-data - NSPredicate 用于检查核心数据中的 NULL 和空白字符串