ユーザーがスクロールしている間に、テーブルビューの下部に行を動的に追加しようとしています。ユーザーはこれに気付かず、「無限に」スクロールできます。insertRowsAtIndexPathsの後にアプリケーションがクラッシュする
ユーザーがテーブルの下の40セルに達すると、100個の新しいセルを下に描画したいと思います。私は
tableView.beginUpdates()
tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .None)
tableView.endUpdates()
を呼び出すとき
はこれでアプリケーションはtableView.endUpdates()
にクラッシュするようだ:
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 10 beyond bounds [0 .. 9]'
私は強く、私はアップデートを実行する前UITableView
のための私のdataProviderが正しく更新されると信じています。私はなぜそれがクラッシュしているのか分かりません。
私はこの目的のために非常に単純な実装を行いました。誰がなぜ以下がクラッシュするのか理解していますか?
private let CellTreshold: Int = 100
var cellCount: Int = 100
@IBOutlet weak var tableView: UITableView!
// UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellCount
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MyCellIdentifier") as! UITableViewCell
cell.index = indexPath.row
return cell
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == cellCount - 40 {
print("indexPath = \(indexPath.row); inserting \(CellTreshold) cells")
var indexPaths = [NSIndexPath]()
let beginIndex = cellCount
let endIndex = cellCount + CellTreshold
for i in beginIndex ..< endIndex {
indexPaths.append(NSIndexPath(forRow: i, inSection: 0))
}
cellCount += CellTreshold
tableView.beginUpdates()
tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .None)
tableView.endUpdates()
}
}
は 'せたbeginIndex = cellCountで試してみてください - 1 '?最後のものの後に挿入しているかもしれません – zcui93
最後のものの後に新しいセルを挿入するのがいいと思います。問題は、関連する単一セルの変更に使用するように設計されたメソッドで挿入が実装されていることです。この時点で、テーブルビュー全体が適切に構成され、新しい行の挿入およびそのような操作は、たとえそれが動作していても動作していても安全ではありません。 –
デバッグして '[0 .. 9]'であることを調べる価値があります。 – zcui93