我正在开发基于CloudKit的项目,使用排序描述符从数据库中获取最新结果非常有用。
func getConversationPosts(for targetConversation: MessageConversation, completionHandler: @escaping ([MessagePost]) -> Void) {
var post = MessagePost()
let getRecordsOperation = CKQueryOperation()
getRecordsOperation.qualityOfService = .userInteractive
getRecordsOperation.resultsLimit = 1
getRecordsOperation.query = CKQuery(recordType: "MessagePost", predicate: NSPredicate(format: "conversationName = %@", targetConversation.conversationID.recordName))
getRecordsOperation.query?.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] // If you comment this out results are returned
/*getPostsOperation.queryCompletionBlock = {(searchCursor, error) in
print("sQ: \(searchCursor)")
}*/
getRecordsOperation.recordFetchedBlock = {(postRecord) in
let newPost = MessagePost()
newPost.textContent = postRecord.value(forKey: "textContent") as! String
newPost.poster = User(userName: postRecord.value(forKey: "postUser") as! String)
// posts.append(newPost)
post = newPost
}
getRecordsOperation.completionBlock = {() in
completionHandler(post)
}
OperationQueue().addOperation(getRecordsOperation)
}
如果删除添加sortDescriptors
的行,则上述代码始终有效。即使没有结果限制,如果添加了任何排序描述符,recordFetchedBlock
甚至不会被调用,但是完成块是。可能导致这种情况的原因是什么?