You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中@ObservedSectionedResults删除数据后数组越界崩溃问题

解决@ObservedSectionedResults删除时索引越界崩溃问题

崩溃原因是直接调用realm.delete(memo)删除数据时,@ObservedSectionedResults的视图更新机制未同步感知数据变化,导致SwiftUI的List尝试访问已失效的索引。核心解决方式是使用@ObservedSectionedResults内置的删除方法,确保数据变更与视图更新同步:

修改删除逻辑

将滑动删除按钮中的手动Realm操作替换为@ObservedSectionedResults的delete方法,同时获取当前条目所在的分组索引和条目索引:

List {
    // 外层ForEach获取分组索引和分组数据
    ForEach(Array(sectionedMemo.enumerated()), id: \.element.id) { sectionIndex, section in
        Section {
            // 内层ForEach获取条目索引和条目数据
            ForEach(Array(section.enumerated()), id: \.element.id) { itemIndex, memo in
                Text(memo.content)
                    .swipeActions(edge: .trailing) {
                        Button{
                            // 使用ObservedSectionedResults的内置删除方法
                            $sectionedMemo.delete(at: sectionIndex, index: itemIndex)
                        } label: {
                            Image(systemName: "trash")
                                .tint(.red)
                        }
                    }
            }
        } header: {
            Text(section.key)
        }
    }
}

原理说明

@ObservedSectionedResults的delete方法会同时处理Realm数据写入和视图更新通知,确保SwiftUI的List能实时同步数据状态,避免索引不一致的问题。手动调用realm.delete绕开了ObservedSectionedResults的更新机制,导致视图仍持有旧的索引信息,从而触发越界崩溃。

额外注意事项

  • 确保Memo模型是符合Realm要求的对象(继承自Object,且firstLetter属性能正确生成分组键)
  • 避免在@ObservedSectionedResults绑定的数据集上执行手动Realm写入操作,优先使用其提供的增删改方法

内容的提问来源于stack exchange,提问作者Ryo Hamasaki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 04:05:13