首页 > 解决方案 > 删除 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.'

第二 func仅从self.currentAccountRealm 中删除,而一个删除Realm 中的所有内容包括 self.currentAccount. 两个funcs 都在同一个 View Controllerclass中,并且都从同一个视图控制器中调用class

如果这很重要,我正在使用领域通知。

有人有什么想法吗?

感谢您的关注!

标签: iosswiftrealm

解决方案


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

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

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

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

然后您可以使用领域浏览器检查该对象是否实际上已被删除。


推荐阅读