3

根据 Apples Class Reference CKQuery,运算符CONTAINS是受支持的运算符之一。但是,这似乎不起作用。我有一个RecordType被叫myRecord和一个字段名称name类型的记录String。我尝试使用两种不同的谓词来获取记录,一种使用“==”运算符,一种使用CONTAINS运算符。

func getRecords() {
    let name = "John"
    let Predicate1 = NSPredicate(format: "name == %@",name)
    let Predicate2 = NSPredicate(format: "name CONTAINS %@",name)

    let sort = NSSortDescriptor(key: "Date", ascending: false)
    let query = CKQuery(recordType: "myRecord", predicate: Predicate1)
    // let query = CKQuery(recordType: "myRecord", predicate: Predicate2)
    query.sortDescriptors = [sort]

    let operation = CKQueryOperation(query: query)
    operation.desiredKeys = ["name", "Date"]

    operation.recordFetchedBlock = { (record) in
        print(record["name"])

        operation.queryCompletionBlock = { [unowned self] (cursor, error) in
            dispatch_async(dispatch_get_main_queue()) {
                if error == nil {

                    print ("sucess")
                } else {
                    print("couldn't fetch record error:\(error?.localizedDescription)")

                }
            }

        }

        CKContainer.defaultContainer().publicCloudDatabase.addOperation(operation)
    }

使用Predicate1,输出为:

Optional(John)
sucess

使用Predicate2,输出为:

couldn't fetch record error:Optional("Field \'name\' has a value type of STRING and cannot be queried using filter type LIST_CONTAINS")

也使用[c]忽略大小写会导致服务器问题。

如何CONTAINS正确使用运算符?

编辑: 我现在仔细查看了文档,发现CONTAINS只能与SELF. 这意味着所有字符串字段都将用于搜索。没有更好的方法吗?

4

1 回答 1

1

It's an exception mentioned as below:

With one exception, the CONTAINS operator can be used only to test list membership. The exception is when you use it to perform full-text searches in conjunction with the self key path. The self key path causes the server to look in searchable string-based fields for the specified token string. For example, a predicate string of @"self contains 'blue'" searches for the word “blue” in all fields marked for inclusion in full-text searches. You cannot use the self key path to search in fields whose type is not a string.

So, you can use 'self' instead of '%K' in order to search sub-text of string field.

For the full document written by Apple

于 2017-04-21T16:41:57.563 回答