简体   繁体   English

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

[英]CloudKit: Order query results by creation date

When loading items from CloudKit I would like to order the results by creation date. 从CloudKit加载项目时,我想按创建日期订购结果。 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. 这是Objective-C解决方案。 It works similarly in Swift. 它在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); CKError 0x12e874f10:“无效参数”(12/2016); server message = "Field '___createTime' is not marked sortable"; server message =“Field'___createTime'未标记为可排序”; uuid = 468AC2A4-24D6-4A56-81BB-6A2A8027DC15; uuid = 468AC2A4-24D6-4A56-81BB-6A2A8027DC15; container ID = "iCloud.com.xxx" container ID =“iCloud.com.xxx”

So, just make it sortable in dashboard: 因此,只需在仪表板中对其进行排序: 在此输入图像描述

Swift - 3.0 斯威夫特 - 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. 您可以使用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. 但是您必须在CloudKit中启用creationDate-field进行查询,以便您可以在查询中使用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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