Pavel B.
Pavel B.

Reputation: 63

CloudKit Fetch First Record Only

I'd like to know how to fetch just the first record from a CloudKit table. For example, I have a table for "Classes" and I only want to get the class that was last modified, instead of getting all of the classes like I do now:

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)")
            }
        }
    }
}

Upvotes: 3

Views: 525

Answers (1)

William T.
William T.

Reputation: 14321

Well, there's 2 things you need for your particular scenario.

  1. Add a sort on "Modified" which is an Apple generated field on every record.
  2. You need to impose a LIMIT on your CKQuery using a CKQueryOperation.

Your code should look something like this:

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)

Upvotes: 4

Related Questions