1

i load tableview data from realm

let tasks = realmManager.objects(ModelTask.self).filter("planId == %@", currentPlan.id)
    datasource = Array(tasks)
    tableViewMain.reloadData()

and delete a item when user click delete in tableview

   func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let delete = UITableViewRowAction(style: .normal, title: "删除".localized) {
        [weak self] action, index in
        guard let `self` = self else {return}

        let task = self.datasource[indexPath.row]

        let realm = try! Realm()
        try? realm.write {
            realm.delete(task)
        }

        self.datasource.remove(at: indexPath.row)
        tableView.reloadData()

    }
    delete.backgroundColor = UIColor(hex:"fe5d5c")

    return [delete]
}

and it crashed when realm delete this item.

i got error message reason: 'Object has been deleted or invalidated.'

i'm confused this works fine at other view controller.

why not work here?

Edit ----------

solved this problem .

because after i delete this item , i have a log function that used this item. that's why it always crash.

thank u everyone

ice.hu
  • 75
  • 1
  • 6
  • Instead of manually removing items from data source and reloading data, why not use NotificationToken like in the official examples? – EpicPandaForce May 02 '18 at 13:00
  • https://stackoverflow.com/questions/31852782/realm-object-has-been-deleted-or-invalidated?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Sharad Chauhan May 03 '18 at 07:01
  • @EpicPandaForce thank u very much problem solved – ice.hu May 03 '18 at 07:05

1 Answers1

0

try this

    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let delete = UITableViewRowAction(style: .normal, title: "删除".localized) {
            [weak self] action, index in
            guard let `self` = self else {return}

            let task = self.datasource[indexPath.row]

            let realm = try! Realm()
            try? realm.write {
                realm.delete(task)
                self.datasource = realmManager.objects(ModelTask.self).filter("planId == %@", currentPlan.id)
            }

            tableView.reloadData()

        }
        delete.backgroundColor = UIColor(hex:"fe5d5c")

        return [delete]
    }

Or you can check isInvalidated before you remove it from data source

if !task.isInvalidated{
    self. datasource.removeObject(task)
}
A.Munzer
  • 1,890
  • 1
  • 16
  • 27
  • even i remove datasource reset and tableview reload, it still crash . I think the problem is delete a task from realm . – ice.hu May 03 '18 at 06:18