从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)")
}
}
}
答案 0 :(得分:17)
这就是我想要的:
query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
答案 1 :(得分:14)
这是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:“无效参数”(12/2016); server message =“Field'___createTime'未标记为可排序”; uuid = 468AC2A4-24D6-4A56-81BB-6A2A8027DC15; container ID =“iCloud.com.xxx”
答案 2 :(得分:0)
let recordInsertDate = records["creationDate"]!
print("recordInsertDate : \(recordInsertDate)")
let query = CKQuery(recordType: "className", predicate: NSPredicate(format: "creationDate >= %@ " , recordInsertDate as! CVarArg))
答案 3 :(得分:-1)
您可以使用NSPredicate。你是对的。
let startDate = NSDate(timeInterval: -60.0 * 120, sinceDate: NSDate())
let predicate = NSPredicate(format: "creationDate > %@", startDate)
但您必须在CloudKit中启用creationDate-field进行查询,以便您可以在查询中使用它们。