首页 > 解决方案 > 在 SwiftUI NavigationLink 视图中删除领域对象

问题描述

我有一个列表视图、行视图(对于列表中的每个元素)和详细视图(将由行视图中的 NavigationLink 打开)。在详细视图中,我有一个删除按钮,我试图删除领域对象并返回列表视图,但我在 AppDelegate 顶部收到以下错误:

由于未捕获的异常“RLMException”而终止应用程序,原因:“对象已被删除或无效。”

详细视图(简单):

struct TransactionDetailView: View {
    
    let realm = try! Realm()
    `Realm Objects which contains some information (title, value ...). Can be null, if the user creates a new one`
    @State var transaction: MyTransaction?
    
    @Environment(\.presentationMode) var presentationMode
    
    var body: some View {...}
                   .navigationBarItems(trailing:
                     Button(action: {
                       if(self.transaction != nil) {
                         try! realm.write {
                           realm.delete(self.transaction!)
                         }
                       }
                       `If i remove this line and go manual back to the list view i have no issues`
                       self.presentationMode.wrappedValue.dismiss()
                    }) {
                       Image(systemName: "trash")
                    })
}
    

列表和行视图(简单):

struct TransactionsView: View {
    
    //get the DB
    let realm = try! Realm()
    
    //get the observable transactions
    @ObservedObject var transactions = BindableResults(results: try! Realm().objects(MyTransaction.self))
    
    var body: some View {
      ...
      List {
        ForEach(transactions) { transaction in
          TransactionRow(transaction: transaction, ...)
        }
      }
    }
}

struct TransactionRow: View {
    var transaction: MyTransaction
    ...
    
    var body: some View {
        NavigationLink(destination: TransactionDetailView(transaction: transaction)){...}
        ...
    }
}

我看不出我的问题为什么它不起作用,但是当我只删除对象并关闭详细视图手册时,一切都会好起来的。

谢谢你的帮助

标签: swiftuirealmswiftui-listswiftui-navigationlink

解决方案


推荐阅读