Crash when deleting Realm data listed by swift: Index 1 is out of bounds

Display the data saved in Realm as a List, I want to be able to view, edit, and delete each cell.

I thought, but every time I delete it Index 1 is out of bounds (must be less than 1) and crashed. I referred to various English sentences for a long time, but I couldn't solve it.

I looked it up after a long time and this article saved me. https://llcc.hatenablog.com/entry/2020/04/26/205254

The understanding of a newcomer like me is that to get a List, you go directly to Realm to get the data. This time, create a View Model for the Cell of the List, create a View Model for the entire View, Get via ViewModel to get List,

ForEach(model.myModels, id: .id) ↓ ForEach(model.cellModels, id: .id) No more going to get deleted or non-existent data

Contents is like this:

private var token: NotificationToken?
    private var myModelResults = try? Realm().objects(MyModel.self)
    @Published var myModels: [MyModel] = []
    
    init() {
        token = myModelResults?.observe { [weak self] _ in
            self?.myModels = self?.myModelResults?.map { $0 } ?? []
        }
    }
    
    deinit {
        token?.invalidate()
    }
ForEach(model.myModels, id: \.id) 

Changed to

private var token: NotificationToken?
    private var myModelResults = try? Realm().objects(MyModel.self)
    @Published var cellModels: [ContentViewCellModel] = []
    
    init() {
        token = myModelResults?.observe { [weak self] _ in
            self?.cellModels = self?.myModelResults?.map { ContentViewCellModel(id: $0.id, title: $0.title) } ?? []
        }
    }
    
    deinit {
        token?.invalidate()
    }
ForEach(model.cellModels, id: \.id)  

By doing this, the error was resolved cleanly.

Recommended Posts

Crash when deleting Realm data listed by swift: Index 1 is out of bounds
LIMIT 11 when data is acquired by irb
[Swift] Get the timing when the value of textField is changed