背景
在我的应用程序中,我存储了一堆对象ID。我使用这些ID进行批处理API调用。 API将每个调用限制为10个ID号。此数据呈现在UITableView上。用户可以添加和删除对象,这可以从数据库中添加或删除对象ID。
我正在使用Firestore数据库存储对象ID。
当前实施
这是我到目前为止所执行的操作,但是在添加和删除对象时会导致应用程序崩溃。我还无法弄清楚如何正确处理这些案件,以及这是否是执行此类操作的正确模式。
var objectIds: [String] = []
var chunkedObjectIds: [[String]] = []
var objects: [Array] = []
var offset: Int = 0
override func viewDidLoad() {
super.viewDidload()
getObjectIds()
}
func getObjectIds() {
// get objects IDs and store then in objectIds from the Firestore database
// setup the .addSnapshotLister so the query is triggered whenever there is a change in the data on Firestore for the collection
return chunkedObjectIds
// when finished, get the first 10 objects from the 3rd party API
fetchObjects()
}
func fetchObjects() {
// split objectIds array in array of arrays, in lots of 10
// chunkedObjectIds is set here
// request the objects for the first 10 ID numbers
Alamofire.request(… parameter with first 10 object ids …) (objects) in {
// save objects
// increment the offset
offset += 1
}
}
在UITableView单元格上呈现数据
使用以下方法从第三方API加载更多数据:
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let lastRow = objects.count
var parameters = [String: Any]()
if indexPath.row == lastRow {
if !(offset == self.chunkedObjectIds.count) {
// process the next batch from the array
parameters["id-numbers"] = self.chunkedObjectIds[offset].map{String($0)}.joined(separator: ",")
Alamofire.request(… paramaters: parameters) { (objects) in
for item in 0..<objects.count {
let indexPath = IndexPath(row: item + self.objects.count, section: 0)
self.paths.append(indexPath)
}
self.objects.append(contentsOf: objects)
self.tableView.beginUpdates()
self.tableView.insertRows(at: self.paths, with: .automatic)
self.tableView.endUpdates()
self.paths.removeAll()
self.offset += 1
}
}
}
}
添加或删除对象:
问题与问题
这非常适合加载初始数据。但是复制会在添加时发生(有时会崩溃)。删除应用程序时,由于超出范围的异常会导致崩溃。
这是一开始使用的正确模式吗?如果是这样,那么我在第一次加载后要处理的情况,尤其是新对象ID的添加和删除,我缺少什么。
我已根据评论中的反馈更改了实现。所以现在,过程是这样的:
willDisplay cell
方法来触发更多数据加载-它似乎比scrollDidEnd
方法更可靠。所以现在该应用程序不再崩溃。 Firestore侦听器存在一些问题,但我将其作为一个单独的问题发布。