核心数据谓词SQL无法解析

时间:2015-04-29 17:22:11

标签: ios sql swift core-data

我一直在努力让我的过滤声明发挥作用。我尝试了很多东西(你可以在我的注释代码中看到)。我想要做的是在用户输入时进行搜索 - 搜索customerObject.firstName,customerObject.lastName和标题 - 如果短语中的任何一个显示这些结果。 .lastName和.firstName是customerObject的属性。

class func searchContainsPredicateEstimateInvoice(searchString: String, existingPredicate: NSPredicate? = nil) -> NSPredicate
    {
        var words = searchString.componentsSeparatedByString(" ")
        var predicateList = [NSPredicate]()
        for word in words
        {
            if count(word) > 0
            {
                var str = NSString(format: "SUBQUERY(%@, $f, $f.%@ CONTAINS[cd] %@) OR SUBQUERY(%@, $l, $l.%@ CONTAINS[cd] %@) OR (%@ CONTAINS[cd] %@)", "\(CUSTOMER_OBJECT_KEY)","\(USER_FIRST_NAME_LOCAL_KEY)" ,word, "\(CUSTOMER_OBJECT_KEY)", "\(USER_LAST_NAME_LOCAL_KEY)", word, ESTIMATE_NAME_KEY, word)
                println(str)
                var pred = NSPredicate(format: "SUBQUERY(%@, $f, $f.%@ CONTAINS[cd] %@) OR SUBQUERY(%@, $l, $l.%@ CONTAINS[cd] %@) OR (%@ CONTAINS[cd] %@)", "\(CUSTOMER_OBJECT_KEY)","\(USER_FIRST_NAME_LOCAL_KEY)" ,word, "\(CUSTOMER_OBJECT_KEY)", "\(USER_LAST_NAME_LOCAL_KEY)", word, ESTIMATE_NAME_KEY, word)

                //var pred = NSPredicate(format: "SUBQUERY(customerObject, $f, $f.firstName CONTAINS[cd] W).@count > 0")
                //var pred = NSPredicate(format: "SUBQUERY(customerObject, $g, $g.firstName CONTAINS[cd] %@).@count > 0", word)
                //var str = NSString(format: "SUBQUERY(%@, $f, $f.%@ CONTAINS[cd] %@) OR SUBQUERY(%@, $l, $l.%@ CONTAINS[cd] %@) OR (%@ CONTAINS[cd] %@)", "\(CUSTOMER_OBJECT_KEY)","\(USER_FIRST_NAME_LOCAL_KEY)" ,word, "\(CUSTOMER_OBJECT_KEY)", "\(USER_LAST_NAME_LOCAL_KEY)", word, ESTIMATE_NAME_KEY, word)
                predicateList.append(pred)
            }
        }

        if existingPredicate != nil
        {
            predicateList.append(existingPredicate!)
        }

        return NSCompoundPredicate(type: .AndPredicateType, subpredicates: predicateList)

    }
    //var pred = NSPredicate(format: "SUBQUERY(%K, $f, $f.%K CONTAINS[cd] %@) OR SUBQUERY(%K, $l, $l.%K CONTAINS[cd] %@) OR (%K CONTAINS[cd] %@)", "\(CUSTOMER_OBJECT_KEY)","\(USER_FIRST_NAME_LOCAL_KEY)" ,word, "\(CUSTOMER_OBJECT_KEY)", "\(USER_LAST_NAME_LOCAL_KEY)", word, ESTIMATE_NAME_KEY, word)

这是日志中显示内容的实际值:

SUBQUERY(customerObject, $f, $f.firstName CONTAINS[cd] W) OR SUBQUERY(customerObject, $l, $l.lastName CONTAINS[cd] W) OR (name CONTAINS[cd] W)

数据模型: enter image description here

1 个答案:

答案 0 :(得分:1)

谓词创建存在一些问题:

  • SUBQUERY仅与多对多关系一起使用(甚至是 然后并不总是需要)。
  • 从不使用NSString(format:)创建谓词。逃避和逃避 引用字符串格式字符串和谓词格式字符串之间的规则 太过分了。
  • 使用%K进行密钥路径替换,而不是%@

因此谓词应该是

let pred = NSPredicate(format: "%K.%K CONTAINS[c] %@ OR %K.%K CONTAINS[c] %@",
    CUSTOMER_OBJECT_KEY, USER_FIRST_NAME_LOCAL_KEY, word,
    CUSTOMER_OBJECT_KEY, USER_LAST_NAME_LOCAL_KEY, word)

假设CUSTOMER_OBJECT_KEY是一对一关系的名称, 和USER_FIRST_NAME_LOCAL_KEY / USER_LAST_NAME_LOCAL_KEY是属性 目标实体。