CloudKit仅获取第一个记录

时间:2015-08-08 00:33:30

标签: ios swift cloudkit ckquery

我想知道如何从CloudKit表中获取第一条记录。例如,我有一个表#34; Classes"而且我只想获得上次修改的类,而不是像现在这样获得所有类:

let pred = NSPredicate(format: "Students CONTAINS %@", studentRecord)
var query = CKQuery(recordType: "Class", predicate: pred)
publicDB.performQuery(query, inZoneWithID: nil) {
    records, error in
    if error != nil {
        println("\(error)")
    } else {
        if records.count > 0 {
            for record in records {
                println("\(record)")
            }
        }
    }
}

1 个答案:

答案 0 :(得分:3)

嗯,您需要为您的特定场景做两件事。

  1. 在"修改"上添加排序这是每个记录上Apple生成的字段。
  2. 您需要使用CKQueryOperation对CKQuery强制使用LIMIT。
  3. 您的代码应如下所示:

    let pred = NSPredicate(format: "Students CONTAINS %@", studentRecord)
    var query = CKQuery(recordType: "Class", predicate: pred)
    let sort = NSSortDescriptor(key: "Modified", ascending: false)
    query.sortDescriptors = [sort]
    var queryOperation = CKQueryOperation (query: query)
    queryOperation.resultsLimit = 1
    queryOperation.recordFetchedBlock = {
        record in
        println("\(record)")
    }
    queryOperation.queryCompletionBlock = {
        queryCursor, error in
        if error != nil {
            println("\(error)")
        }
    }
    publicDB.addOperation(queryOperation)