LoginSignup
2
2

More than 3 years have passed since last update.

【Swift】Realmでproblem 'Index is out of bounds (must be less than 1)とエラーが出たときの対処法

Last updated at Posted at 2021-03-06

RealmでTableViewにデータを表示しようとした時、タイトルのエラーが起きたので対応方法を記します。
このエラーはRealmのデータ更新時、Realmに保存されているモデルの件数と表示されているTableViewの件数(TableViewの認識している件数が以前のままで)の整合性がとれなくエラーになるようです。

var participants: Results<Participant>?

// cellにデータを表示
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: CELL_ID) as! AttendanceTableViewCell
    cell.delegate = self
    cell.index = indexPath
    cell.textLabel?.text = participants?[save:indexPath.row].name
 }

 // Resultsを拡張
extension Results {
subscript (save index: Int) -> Element? {
    if index < self.count {
        return self[index]
    } else {
        return nil
    }
}

}

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2