How to fix a crash when deleting Realm data in Swift UI List

Crash with Index is out of bounds!

Pass the following method to perform with .onDelete of List of SwiftUI,

func deleteRow(offsets: IndexSet) {
      guard  let index = offsets.first else {
           return
      }
      let deleteItem = hoges[index]
      try! realm.write {
        realm.delete(deleteItem)
      }
      self.hoges = realm.objects(Hoge.self)
}

As a test, when I wrote it like this, it crashed with the error "Index ~ is out of bounds (must be less than ~)."

~~ How to write without crashing ~~

https://stackoverflow.com/questions/61165998/how-to-delete-data-from-swiftui-list-and-realm

~~ If you refer to here and turn the index with forEach, it will not crash! ~~

func deleteRow(offsets: IndexSet) {
      offsets.forEach({ index in
       try! realm.write {
         realm.delete(self.hoges[index])
        }
      })
      self.hoges = realm.objects(Hoge.self)
}

Postscript: I thought that it was fixed by the above, but it only stopped crashing when the last data was deleted, and it crashed as well when I deleted other cells. I customized forEach by referring to the information that came out by google, and I made an exist method to check if the data exists, but none of them worked,

Make a Model

Temporarily referring to this article, create a Model that defines the same value as the Realm data defined by @objc dynamic var with a struct, substitute it from Realm with the initializer of ViewModel, and directly from List Realm I avoided the crash by taking the value from the Model without referring to.

import RealmSwift

class Hoge: Object, Identifiable {
    @objc dynamic var id: String = ""
    @objc dynamic var title: String = ""
    
    override static func primaryKey() -> String? {
        return "id"
    }
}
struct HogeModel {
    let id: String
    let title: String
}

https://llcc.hatenablog.com/entry/2020/04/26/205254

This method may be quite troublesome if the development scale is large.

There seems to be a similar issue for RealmSwift, but I hope it will be even easier to use with SwiftUI! https://github.com/realm/realm-cocoa/issues/6635

Use Frozen Objects (20/11/16 postscript)

While searching for further improvements, I found out that there are Frozen Objects that can handle Realm Results immutable. https://realm.io/blog/realm-database-a-new-architecture-and-frozen-objects/

I haven't figured out how to use it in detail yet, but I found an easier way than recreating the Model. self.hoges = realm.objects(Hoge.self)?.freeze() I really want to write it like this, but if I declare it like this and perform an operation that uses realm.write such as delete, it will crash. So, tentatively, when you set the immutable property to Published and write it with the initializer or realm.write, you can avoid the crash by assigning it!

HogeViewModel.swift


  var hoges: Results<Hoge>?
  @Published var freezedHoges: Results<Hoge>?

  let realm = try! Realm()
    
  init() {
    hoges = realm.objects(Hoge.self)
    freezedHoges = hoges?.freeze()
  }

  func addHoge() {
    let hoge = Hoge()
    hoge.id = NSUUID().uuidString
    hoge.title = "fuga"
    try! realm.write {
      realm.add(hoge)
    }
    freezedHoges = hoges?.freeze()
  }
 

Recommended Posts

How to fix a crash when deleting Realm data in Swift UI List
[Swift] How to fix Label in UIPickerView
How to overwrite Firebase data in Swift
Crash when deleting Realm data listed by swift: Index 1 is out of bounds
How to clear all data in a particular table
How to create a data URI (base64) in Java
How to store Rakuten API data in a table
How to change BackgroundColor etc. of NavigationBar in Swift UI
[Swift] How to send a notification
How to output a list of strings in JSF as comma-separated strings
How to sort a List using Comparator
[swift5] How to specify color in hexadecimal
How to get date data in Ruby
Try to display a slightly rich Webview in Swift UI using UIViewRepresentable
[Java] How to add data to List (add, addAll)
How to fix system date in JUnit
How to give MAX + 1 ID to registered data when adding a new record
[Swift5] How to create a splash screen
How to pass a proxy when throwing REST over SSL in Java
How to publish a library in jCenter
How to reference a column when overriding the column name method in ActiveRecord
How to get the ID of a user authenticated with Firebase in Swift
How to store data simultaneously in a model associated with a nested form (Rails 6.0.0)
How to make a unique combination of data in the rails intermediate table
Precautions when saving data in Realm (distinguishing between Managed / Unmanaged, when to use copyToRealm ())
[Rails] How to write when making a subquery
How to display a web page in Java
How to add sound in the app (swift)
How to run a djUnit task in Ant
How to add a classpath in Spring Boot
How to create a theme in Liferay 7 / DXP
How to implement a like feature in Rails
[Swift UI] How to disable ScrollsToTop of ScrollView
How to easily create a pull-down in Rails
How to make a follow function in Rails
How to execute tasks in parallel in Swift in Swift Package
How to log in automatically when Ubuntu restarts
How to automatically generate a constructor in Eclipse
How to save a file with the specified extension under the directory specified in Java to the list
[Swift] How to display the entered characters in Widget via UserDefaults when using WidgetKit
How to implement UICollectionView in Swift with code only
How to create a Java environment in just 3 seconds
How to implement a like feature in Ajax in Rails
How to create a Spring Boot project in IntelliJ
How to launch another command in a Ruby program
How to display a browser preview in VS Code
[How to insert a video in haml with Rails]
How to write a date comparison search in Rails
How to mock a super method call in PowerMock
How to convert A to a and a to A using AND and OR in Java
[Swift] Use UserDefaults to save data in the app
[swift5] How to execute processing when tabBar is tapped
How to convert a file to a byte array in Java
[Rails 6] How to set a background image in Rails [CSS]
[Rails] How to load JavaScript in a specific view
How to write a core mod in Minecraft Forge 1.15.2
How to launch Swagger UI and Swagger Editor in Docker
[Ruby/Rails] How to generate a password in a regular expression
How to perform a specific process when the back button is pressed in Android Fragment
A memorandum when I investigated how to convert from Epoch Time to Date type in Scala
How to write in Model class when you want to save binary data in DB with PlayFramework