NSPredicate在SUBQUERY中

时间:2016-04-19 13:49:37

标签: swift core-data nspredicate nsexpression

我正在尝试为NSPredicate写一个SUBQUERY。我的问题是我手头没有查询SUBQUERY的谓词部分。有没有办法在SUBQUERY中嵌套NSPredicate?

例如,这就是我的尝试:

let ordersPredicate = NSPredicate()//some predicate passed in
//how do I use the ordersPredicate inside the subquery??
let subQueryPredicate = NSPredicate(format: "SUBQUERY(orders, $x,'%@').@count > 0", ordersPredicate.predicateFormat)

更新:我现在必须通过执行第一个谓词并执行ANY IN查询来做一个肮脏的解决方法。它的跛脚:(因为我正在其他地方执行ordersPredicate以及以后的管道..

let fetchRequest = NSFetchRequest()//blah
fetchRequest.predicate = orderPredicate
let orders = //execute fetch
let subQueryPredicate = NSPredicate(format: "SUBQUERY(orders, $x, ANY $x in %@).@count > 0", orders)

2 个答案:

答案 0 :(得分:2)

感谢@Willeke的一些指示,我能够提出解决方案。

await RunFirstOperationAsync()
    .ContinueWith(t => RunSecondOperationAsync());

这是用法

public extension NSPredicate{
    public func stringForSubQuery(prefix:String) -> String{
        var predicateString = ""
        if let predicate = self as? NSCompoundPredicate{
            for (index, subPredicate) in predicate.subpredicates.enumerate(){

                if let subPredicate = subPredicate as? NSComparisonPredicate{
                    predicateString = "\(predicateString) \(prefix)\(subPredicate.predicateFormat)"
                }
                else if let subPredicate = subPredicate as? NSCompoundPredicate{
                    predicateString = "\(predicateString) (\(subPredicate.stringForSubQuery(prefix)))"
                }
                //if its not the last predicate then append the operator string
                if index < predicate.subpredicates.count - 1 {
                    predicateString = "\(predicateString) \(getPredicateOperatorString(predicate.compoundPredicateType))"
                }
            }
        }
        return predicateString
    }
    private func getPredicateOperatorString(predicateType: NSCompoundPredicateType) -> String{
        switch(predicateType){
        case .NotPredicateType: return "!"
        case .AndPredicateType: return "&&"
        case .OrPredicateType: return "||"
        }
    }
}

答案 1 :(得分:2)

对于以后遇到此问题的任何人,您都不需要自己构建谓词字符串,只需直接在子查询字符串中使用predicateFormat。已经正确转义了,因此请使用字符串插值。

let ordersPredicate = NSPredicate()
// Add it to the query with string interpolation
let subQueryPredicate = NSPredicate(format: "SUBQUERY(orders, $x, \(ordersPredicate.predicateFormat)).@count > 0")

如果您尝试将其作为参数传递,它将尝试再次转义字符串,这可能无法正常工作。

// Don't do this!
let subQueryPredicate = NSPredicate(format: "SUBQUERY(orders, $x, %@).@count > 0", ordersPredicate.predicateFormat)