从CloudKit中的Record中仅检索一个值

时间:2016-02-03 11:59:17

标签: ios cloudkit

我正在学习使用CloudKit,最后设法检索/查询硬编码到仪表板中的数据。我正在尝试使用CKQueryOperation仅从记录中查询一个值,但我总是收到每个记录中的所有值。 在我的下面的代码中,我试图通过使用desiredKey属性来获得“年龄”值 - 我得到的是“age”,“firstName”,“lastName”等等。

let container = CKContainer.defaultContainer()
let publicData = container.publicCloudDatabase

// select all records
let predicate = NSPredicate(format: "TRUEPREDICATE", argumentArray: nil)
let query = CKQuery(recordType: "quizRecord", predicate: predicate)

// get just one value only
let operation = CKQueryOperation(query: query)
operation.desiredKeys = ["age"]


   // addOperation
    publicData.addOperation(operation)

publicData.performQuery(query, inZoneWithID: nil) { results, error in
    if error == nil { // There is no error
        // PROBLEM .. this prints out all values ????
        print(results)
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
        })
    }
    else {
        print(error)
    }
}

////以下/修改过的代码可以正常工作

    let container = CKContainer.defaultContainer()
    let publicData = container.publicCloudDatabase

    // select all records
    let predicate = NSPredicate(format: "TRUEPREDICATE", argumentArray: nil)
    let query = CKQuery(recordType: "quizRecord", predicate: predicate)

    // get just one value only
    let operation = CKQueryOperation(query: query)
    operation.desiredKeys = ["age"]


    // get query
    operation.recordFetchedBlock = { (record : CKRecord) in
        // process record

        print(record)

    }


    // operation completed
    operation.queryCompletionBlock = {(cursor, error) in
        dispatch_async(dispatch_get_main_queue()) {
            if error == nil {

                print("no errors")
                // code here

            } else {

                print("error description = \(error?.description)")
            }
        }
    }

        // addOperation
    publicData.addOperation(operation)

1 个答案:

答案 0 :(得分:2)

问题很简单。您在desiredKeys上设置CKQueryOperation但实际上从未使用过此操作。您改为在数据库上使用performQuery

如果要使用该操作并将数据限制为特定键,则需要将操作添加到数据库(使用addOperation:),而不是调用performQuery。当然,您需要为操作的一个或多个recordFetchedBlockqueryCompletionBlock属性分配一个块。

let container = CKContainer.defaultContainer()
let publicData = container.publicCloudDatabase

// select all records
let predicate = NSPredicate(format: "TRUEPREDICATE", argumentArray: nil)
let query = CKQuery(recordType: "quizRecord", predicate: predicate)

// get just one value only
let operation = CKQueryOperation(query: query)
operation.desiredKeys = ["age"]

operation.recordFetchBlock = { (record : CKRecord) in
    // process record
}
operation.queryCompletionBlock = { (cursor : CKQueryCursor!, error : NSError!) in
    // Query finished
}

// addOperation
publicData.addOperation(operation)