无法使用 SwiftUi 上的列表删除 Realm 上的所有元素

问题描述 投票:0回答:1

我有一个显示所有元素的列表。我想添加一个按钮,从列表中删除所有元素,同时也从领域数据库中删除所有元素。 我很清楚删除领域对象后无法调用它,但是我无法理解为什么当我单击“全部删除”按钮时出现此错误:对象已被删除或失效 这是我的代码: 设置视图:

import SwiftUI

struct SettingsView: View {
    
    @Binding var showSetting: Bool
    
    
    @State var allAction01: [Action] = []
    @State var allAction12: [Action] = []
    
    init(showSetting: Binding<Bool>) {
        self._showSetting = showSetting
    }
    
    var body: some View {
        NavigationStack {
                List{
                    
                    Section{
                    
                        Button(action: deleteAll){
                            Text("Delete")
                                .foregroundStyle(.red)
                        }
                            .buttonStyle(.plain)
                    } // Section
                    
                    Section {
                        Text("Liste des actions")
                            .fontWeight(.bold)
                            .font(.system(size: 20))
                    } // Section
                    
                    Section {
                        ForEach(allAction01, id: \.id) { action in
                            Text(action.text)
                        }
                        .onDelete(perform: delete)
                
                    
                    Section {
                        ForEach(allAction12, id: \.id) { action in
                            Text(action.text)
                        }

                } // List
                .onAppear(perform: updateAction)                    
        } // NavigationStack
    } // var body: some View
    
    private func delete(indexSet: IndexSet){
        indexSet.forEach { index in
            DataManager.deleteAction(action: allAction01[index])
        }
        updateAction()
    } // private func delete(indexSet: IndexSet)
    

    private func deleteAll(){
        DataManager.deleteAllActions()
        updateAction()
    }
    
    private func updateAction(){
        allAction01 = DataManager.getActionBetween(inf: 0, sup: 1)
        allAction12 = DataManager.getActionBetween(inf: 1, sup: 2)
   
    }
} // struct SettingsView: View

这是我的

DataManager.deleteAllActions()

    static func deleteAllActions() {
        do {
            try realm.write(){
                let actionToDelete = realm.objects(Action.self)
                realm.delete(actionToDelete)
            }
        } catch {
            print("Error : \(error)")
        }
    }

如果您有任何想法,我真的会帮助我!

PS:我将我的 SettingsView 显示为覆盖另一个视图的工作表,但仅删除一个操作时不会导致任何问题。

我尝试删除我的所有操作,我希望在此之后有一个空的 BDD 和列表

swift swiftui realm
1个回答
0
投票

核心问题是使用数组来保存 Realm 数据。

虽然从 Realm 中删除对象会删除底层对象,这也会使数组中的对象无效,但它不会从数组中删除索引。

举个例子,假设如下;有一个 PersonClass 对象,Realm 中存储了 5 个人。

let personResults = realm.objects(PersonClass.self) //get 5 persons
let personArray = Array(personResults) //instantiate an array with 5 persons

print(personResults.count) //prints 5
print(personArray.count) // also prints 5

try! realm.write {
    realm.delete(personResults) //delete the persons from Realm
}

print(personResults.count) //prints 0 as there are no persons in Realm
print(personArray.count) //print 5 since 5 indexes exist, containing nil objects

有多种方法可以解决这个问题

  1. 从 Realm 中删除对象时,也将其从数组中删除

  2. 使用 @ObservedRealmObject 来处理特定对象,或者在此用例中,使用 @ObservedResults 属性包装器,其定义为:

观察查询结果的集合。您可以执行快速写入 到 ObservedResults 集合,视图会自动更新 当观察到的查询发生变化时自身。例如,您可以删除 使用 onDelete 从观察到的狗列表中选择狗。

用这些内容替换当前的变量将解决问题

@ObservedResults(Action.self) var actions01
//@State var allAction12: [Action] = []

init(showSetting: Binding<Bool>) {
   self._showSetting = showSetting
}

var body: some View {
   NavigationStack {
      List {
         //use actions01 here for the UI
     

并使用action01作为列表数据源。然后,当删除所有操作时,视图将自动,因为 actions01 将始终反映底层数据的当前状态 - 对象被删除,它从操作 01 中删除,UI 也会相应更新。

结果可以像只读数组一样对待;迭代它,访问特定索引等。它无法写入 - 写入 Realm 来更新结果

© www.soinside.com 2019 - 2024. All rights reserved.