我有2个函数loadData和loadMore,如下所示:
import UIKit
import CloudKit
class HireView: UIViewController, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate, UIScrollViewDelegate, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var tableView: UITableView!
let myData = CKContainer.default().publicCloudDatabase
let predicate = NSPredicate(value: true)
override func viewDidLoad() {
super.viewDidLoad()
self.loadData()
}
func loadData(){
var result = [CKRecord]()
let query = CKQuery(recordType: "Hire", predicate: predicate)
query.sortDescriptors = [NSSortDescriptor(key: "postDate", ascending: false)]
let operation = CKQueryOperation(query: query)
operation.resultsLimit = 100
operation.qualityOfService = .userInteractive
operation.recordFetchedBlock = { (record) in
DispatchQueue.main.async {
result.append(record)
hireItems = result
self.tableView.reloadData()
}
}
operation.queryCompletionBlock = { (cursor, error) in
if error != nil {
} else {
if result.isEmpty == true {
DispatchQueue.main.async {
hireItems = result
self.tableView.reloadData()
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
myData.add(operation)
}
func loadMore(){
let query = CKQuery(recordType: "Hire", predicate: predicate)
query.sortDescriptors = [NSSortDescriptor(key: "postDate", ascending: false)]
let operation = CKQueryOperation(query: query)
operation.resultsLimit = hireItems.count + 100
operation.qualityOfService = .userInteractive
operation.recordFetchedBlock = { (record) in
if (record["postDate"] as! Date) < (hireItems[hireItems.count - 1]["postDate"] as! Date) {
DispatchQueue.main.async {
hireItems.append(record)
self.tableView.reloadData()
}
}
}
operation.queryCompletionBlock = { (cursor, error) in
if error != nil {
DispatchQueue.main.async {
}
} else {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
myData.add(operation)
}
}
我的问题是:
loadMore()
功能最好吗?
有没有办法让loadMore()
更好?
答案 0 :(得分:0)
更好的方法可能是使用CKQueryOperation queryCompletionBlock
中返回的CKQueryCursor。
如果此光标不是nil
,那么您将有更多记录等待获取。要继续抓取,您应该使用init(cursor: CKQueryCursor)初始值设定项。
使用此方法初始化检索的查询操作 上一次搜索的下一批结果。