CloudKit: 按创建日期排序查询结果

CloudKit: Order query results by creation date

从 CloudKit 加载项目时,我想按创建日期对结果进行排序。我相信现在它是按记录的第一个 属性 排序的。

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

您可以使用 NSPredicate。你是对的。

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

但是您必须在 CloudKit 中启用 creationDate-field 进行查询,以便您可以在查询中使用它们。

这就是我要找的:

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

这是一个 Objective-C 解决方案。它在 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]];

这样,您可能会收到以下错误消息:

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"

因此,只需使其在仪表板中可排序即可:

Swift - 3.0

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