ios - 删除 Realm 对象会导致一个函数崩溃,而不是另一个函数

标签 ios swift realm

我有两个几乎相同的函数。这个工作正常:

func deleteEveryDamnThing(){
    let allAccounts = realm.objects(Account.self)
    let allTransactions = realm.objects(Transaction.self)

    try! realm.write {
        realm.delete(allAccounts)
        realm.delete(allTransactions)
    }
    self.activeAcctLabel.text = "No Active Account"
    self.currentBalLabel.text = "$0.00"
    self.highBalLabel.text = "$0.00"
    self.balBarTopConstraint.constant = 505
    self.balanceBar.backgroundColor = UIColor.red
    self.currentBalLabel.textColor = UIColor.red
    self.littleDash.backgroundColor = UIColor.red
    self.popNoActiveAccountAlert()
}

但是,这个:

func actuallyDeleteCurrentAccount(){
    let thisAccount = self.currentAccount

    try! realm.write {
        realm.delete(thisAccount)
    }
    self.activeAcctLabel.text = "No Active Account"
    self.currentBalLabel.text = "$0.00"
    self.highBalLabel.text = "$0.00"
    self.balBarTopConstraint.constant = 505
    self.balanceBar.backgroundColor = UIColor.red
    self.currentBalLabel.textColor = UIColor.red
    self.littleDash.backgroundColor = UIColor.red
    self.popNoActiveAccountAlert()
}

因解释而崩溃:

Terminating app due to uncaught exception 'RLMException', reason: 'Object has been deleted or invalidated.'

second func 仅从 Realm 中删除 self.currentAccount,而 first 删除 Realm 中的所有内容包括 self.currentAccount。两个 func 都在同一个 View Controller class 中,并且都从同一个 class 调用。

如果重要的话,我正在使用 Realm 通知。

有人有什么想法吗?

感谢您的关注!

最佳答案

我认为问题可能是您调用了函数 actuallyDeleteCurrentAccount() 两次,或者它正在从其他地方删除。

另一个原因可能是在您的通知 token 上,您假设您的对象存在但该对象刚刚被删除。

我建议您使用一些打印或断点来缩小问题范围。 你也可以像这样做一些检查

    try! realm.write {
        thisAccount.invalidated == false {
            realm.delete(thisAccount)
        }
        //otherwise the object is already invalidated
    }

然后您可以使用 Realm 浏览器来检查该对象是否确实被删除了。

关于ios - 删除 Realm 对象会导致一个函数崩溃,而不是另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52249594/

相关文章:

ios - 调度线程组错误

ios - Facebook iOS SDK ExtendAccessToken无法正常工作-无法调用fbDidExtendToken

Swift 扩展协议(protocol)

ios - 将数据库保存在 AppGroup 的共享容器中是一种好方法吗

ios - 如何隐藏一些单元格以进行编辑 View

ios - 以编程方式更改应用名称

swift - 声明文本字段变量在 if 语句中多次工作 (swift4)

swift - 取消可选在 BST 实现中不起作用

ios - RealmSwift 查询中带有内部对象引用的谓词问题

java - 使用 RealmSearchView 时出现 Android DuplicateFileException