2016-02-12 18 views
1

根據Apples Class Reference CKQuery,運算符「CONTAINS」是其中一個支持的運算符。但是,這似乎並不奏效。我有一個名爲myRecord的記錄類型,以及一個帶有「name」字符串的記錄。我嘗試用兩個不同的謂詞獲取記錄,一個使用「==」運算符,另一個使用「CONTAINS」運算符。使用「CONTAINS」運算符時,使用NSPredicate的CKQuery失敗

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,outout是: 可選(約翰) sucess

使用Predicate2,outout是: 無法提取記錄錯誤:可選(「域\ '的名字\' 的值類型STRING且無法使用過濾器類型LIST_CONTAINS查詢「)

還使用[c]忽略腸衣會導致崩潰。

如何正確使用運算符「CONTAINS」。

編輯: 我現在仔細看了看文檔,看到CONTAINS只能用於自己。這意味着所有的字符串字段將用於搜索。沒有更好的方法嗎?

回答

0

這是如下所述的異常:

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.

所以,你可以以搜索字符串字段的子文,而不是使用「%K」「自我」。

For the full document written by Apple