简体   繁体   中英

CloudKit: Order query results by creation date

When loading items from CloudKit I would like to order the results by creation date. I believe now it's sorting by the first property of the record.

func loadItems() {
    let predicate = NSPredicate(value: true)
    let query = CKQuery(recordType: "Items", predicate: predicate)
    db.performQuery(query, inZoneWithID: nil) { (results, error) -> Void in
        if error != nil {
            println(error.localizedDescription)
        }

        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            items = results as [CKRecord]
            self.tableView.reloadData()
            println("items: \(items)")
        }
    }
}

这就是我要找的东西:

query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

Here is an Objective-C solution. It works similarly in Swift.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"TRUEPREDICATE"];
CKDatabase *privateDatabase = [self.myContainer privateCloudDatabase];
CKQuery *query = [[CKQuery alloc] initWithRecordType:@"command" predicate:predicate];
query.sortDescriptors = [NSArray arrayWithObject:[[NSSortDescriptor alloc]initWithKey:@"creationDate" ascending:true]];

With this, you may get the following error message:

CKError 0x12e874f10: "Invalid Arguments" (12/2016); server message = "Field '___createTime' is not marked sortable"; uuid = 468AC2A4-24D6-4A56-81BB-6A2A8027DC15; container ID = "iCloud.com.xxx"

So, just make it sortable in dashboard: 在此输入图像描述

Swift - 3.0

let recordInsertDate = records["creationDate"]!
print("recordInsertDate : \(recordInsertDate)")
let query = CKQuery(recordType: "className", predicate: NSPredicate(format: "creationDate >= %@ " , recordInsertDate as! CVarArg))

You can use NSPredicate. You were right.

let startDate = NSDate(timeInterval: -60.0 * 120, sinceDate: NSDate())
let predicate = NSPredicate(format: "creationDate > %@", startDate)

But you have to enable the creationDate-field in the CloudKit for querying so that you can use them in a query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM