用于从 cloudkit 中检索单列的代码模式/片段

Code pattern / snippet for retrieving single column from cloudkit

我正在构建一个允许用户从公共商店上传/下载信息的应用程序。我认为 cloudKit 存储空间对此非常理想。

我希望用户能够通过关键字字段在商店中搜索记录,然后在 select 找到一条记录时下载整条记录。

用 SQL 术语来说就是:

SELECT id,KeyWords from myDB WHERE KeyWords LIKE %searchstring%

其次是:

SELECT * FROM myDB WHERE id = selectedID

我一直在使用此代码模式从 cloudKit 存储中检索记录:

var publicDatabase: CKDatabase?
let container = CKContainer.defaultContainer()

override func viewDidLoad() {
    super.viewDidLoad()
    publicDatabase = container.publicCloudDatabase
}

func performQuery(){
    let predicate = NSPredicate(value: true)
    let query = CKQuery(recordType: "Library", predicate: predicate)
    publicDatabase?.performQuery(query, inZoneWithID: nil,
        completionHandler: ({results, error in

        ...
        [code to handle results / error here]
        ...
    })
}

但是这个returns所有每条记录的内容,里面有很多不必要的信息。

我只想从 cloudkit 条记录中提取一个字段。

有没有简单的方法可以做到这一点,有人有代码片段吗?

CKFetchRecordsOperation 允许下载受限列,但需要您知道要下载的记录的 ID。

为此,您可以在 CKQueryOperation 上使用 desiredKeys 属性。有关详细信息,请参阅:desiredkeys documentation

好的,有一些工作。这可能很老套,但我把它贴出来供处于相同情况的其他人参考...

let predicate = NSPredicate(value: true) // returns all - replace with whatever condition you want
let query = CKQuery(recordType: "Library", predicate: predicate) // create a query using the predicate
var operation = CKQueryOperation(query: query) // create an operation using the query
operation.desiredKeys = ["KeyWords"] // Array of whatever 'columns' you want to return
// operation.resultsLimit = 15 // optional limit on records

// Define a closure for what to do for each returned record
operation.recordFetchedBlock = { [weak self] (record:CKRecord!) in

    // Do whatever you want with each returned record  
    println(record.objectForKey("KeyWords"))

}

// Define a closure for when the operation is complete
operation.queryCompletionBlock = { [weak self] (cursor:CKQueryCursor!, error:NSError!) in

        if cursor != nil {
            // returns the point where the operation left off if you want t retrieve the rest of the records
        }

        dispatch_async(dispatch_get_main_queue(), { () -> Void in

            // Do what you want when process complete
            self!.tableView.reloadData()
            if error != nil {
                println("there was an error")
            }
        })
    }

self.publicDatabase!.addOperation(operation) // Perform the operation on given database