添加到NSCompoundPredicate

时间:2015-05-10 17:28:56

标签: ios iphone swift

我想让我的代码更可重用于核心数据,我有一个带有谓词的fetchRequest,我总是必须使用它。然而,一些方法需要更多条件。我想将这些条件添加到谓词列表中,但我不确定如何执行此操作。我想要一个方法来返回带有基本查询的谓词,然后添加到那些查询。

 let fetchRequest = NSFetchRequest(entityName: "Stop")

        var currentTime = NSDate.getTime()

        var sort = NSSortDescriptor(key: "time", ascending: true) // sort by bus stop

        fetchRequest.sortDescriptors = [sort]

        let predicate = NSPredicate(format: "time >= %ld", currentTime)

        let predicate2 = NSPredicate(format: "stop_name == %@", stop)

        let predicate3 = NSPredicate(format: "busParent.direction == %@", direction)

        let predicate4 = NSPredicate(format: "busParent.name == %@", name)

        let predicate5 = NSPredicate(format: "busParent.schedule == %ld", schedule)

        fetchRequest.predicate = NSCompoundPredicate.andPredicateWithSubpredicates(
            [predicate, predicate2, predicate3, predicate4, predicate5])

        // EXAMPLE:  HOW WOULD I ADD TO THE COMPOUND PREDICATE ALREADY MADE?
        fetchRequest.predicate.????

1 个答案:

答案 0 :(得分:2)

您可以将NSCompoundPredicates与其他NSPredicates复合:

    let currentPredicate = fetchRequest.predicate!
    let additionalPredicate = NSPredicate(format: "whatever",...)
    let nextPredicate = NSCompoundPredicate(type: NSCompoundPredicateType.AndPredicateType, subpredicates: [currentPredicate, additionalPredicate])
    fetchRequest.predicate = nextPredicate

通过指定.AndPredicateType,您将"缩小"现有结果也适用于那些也符合额外谓词的结果。但您也可以指定OrPredicateTypeNotPredicateType来添加或排除(分别)现有结果。