Realmのデータが表示されているTableViewに、追加ボタンを押すと空データを追加すると同時に、最後のセルの後に空のテキストボックス付きの新しいセルを追加する処理を作りたいと思っています。(iOS標準のリマインダーアプリのようなイメージです)
しかし、追加ボタンを押すとエラーが出てしまいます。
該当部分は以下です。
swift
1 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 2 if segue.identifier == "toAdd" { 3 let item = TodoItem() 4 item.id = String(Int.random(in: 0...9999)) 5 try! realm.write{ 6 realm.add(item) 7 } 8 let indexPath = IndexPath(row: itemList.count - 1, section: 0) // 追加するデータに対応するインデックスパスを取得する 9 tableView.insertRows(at: [indexPath], with: .automatic) // 追加したデータに対応するセルを挿入する 10 } 11 }
https://teratail.com/questions/273185
↑こちらのページを参考に作成したのですが、
以下のエラーが出てしまっています。
既にRealmには2件データが入っている所に、新たに1件データを追加しようとしている状況です。
正しいインデックスパス(3,0)は取得できているはずなので、エラーへの理解が追いついていないのが現状です。
Thread 1: "Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (3) must be equal to the number of rows contained in that section before the update (3), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out). Table view: <UITableView: 0x14e842c00; frame = (0 291; 375 376); clipsToBounds = YES; autoresize = RM+BM; gestureRecognizers = <NSArray: 0x600003969fb0>; layer = <CALayer: 0x6000036dcd20>; contentOffset: {0, 0}; contentSize: {375, 175}; adjustedContentInset: {0, 0, 0, 0}; dataSource: <Todo.ViewController: 0x14d70b020>>"
ご回答頂けますと幸いです。

回答2件
あなたの回答
tips
プレビュー