ios - 从 CloudKit 中的记录中仅检索一个值
<p><p>我正在学习使用 CloudKit,并最终设法检索/查询硬编码到仪表板中的数据。我正在尝试使用 <code>CKQueryOperation</code> 从记录中仅查询一个值,但我总是收到每条记录中的所有值。
在下面的代码中,我试图通过使用 <code>desiredKey</code> 属性来获取“年龄”值 - 我得到的是“年龄”、“名字”、“姓氏”等。</p>
<pre><code>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)
}
}
</code></pre>
<p>////以下/修改后的代码可以正常工作</p>
<pre><code> 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)
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>问题很简单。您在 <code>CKQueryOperation</code> 上设置了 <code>desiredKeys</code>,但实际上从未使用过该操作。您改为在数据库上使用 <code>performQuery</code>。</p>
<p>如果要使用操作并将数据限制到特定键,则需要将操作添加到数据库中(使用<code>addOperation:</code>)而不是调用<code>performQuery</code> .当然,您需要将 block 分配给操作的一个或多个 <code>recordFetchedBlock</code> 和 <code>queryCompletionBlock</code> 属性。</p>
<pre><code>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)
</code></pre></p>
<p style="font-size: 20px;">关于ios - 从 CloudKit 中的记录中仅检索一个值,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/35176467/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/35176467/
</a>
</p>
页:
[1]