jannej
jannej

Reputation: 906

Deleting an object in Realm and keeping tableview in sync

I am trying to understand what I am doing wrong here.

Have two basic viewControllers: a tableView and a detailView.

I am subscribing to notification to reload the tableView if the data is modified. I can modify a record from the detailViewController, and the changes get reflected. Even delete a record from the tableView, and it works.

BUT I would also like to add a delete button on the detailView, but then the viewController and Realm gets out of sync and crashes. 'RLMException', reason: 'Object has been deleted or invalidated.'. The next time I load the app the record is deleted so it works.

How can I delete an object in a different viewController and keep the tablieView controller updated?

class TableViewController: UITableViewController {
    var token:NotificationToken?
    var expenses: Results<Expense> {
    get {
        let realm = try! Realm()
        return realm.objects(Expense.self)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let realm = try! Realm()
        token = realm.addNotificationBlock { [weak self] notification, realm in
        DispatchQueue.main.async {
            self?.tableView.reloadData()
        }
    }
}

class DetailViewController {
     func deleteButtonTapped() {
         let realm = try! Realm()
         if let expense = self.expense {
             try! realm.write {
             realm.delete(expense)
         }
         // crashes during load
         performSegue(withIdentifier: "unwindToExpensesTable", sender: self) 
    }
}

Upvotes: 2

Views: 626

Answers (1)

jervine10
jervine10

Reputation: 3077

Make sure you aren't retaining any references to the deleted Expense object. After deleting the object clear out any reference you may have in DetailViewController, also make sure it isn't in an array somewhere that you might access it again.

Upvotes: 1

Related Questions