只能从它所属的Realm中删除一个对象

时间:2017-05-09 04:01:27

标签: swift uitableview realm

我收到此错误" 只能删除其所属领域的对象"每次我尝试从我的tableview上的域中删除一个对象。以下是相关代码:

let realm = try! Realm()
var checklists = [ChecklistDataModel]()

override func viewWillAppear(_ animated: Bool) {


    checklists = []
    let getChecklists = realm.objects(ChecklistDataModel.self)

    for item in getChecklists{

        let newChecklist = ChecklistDataModel()
        newChecklist.name = item.name
        newChecklist.note = item.note

        checklists.append(newChecklist)
    }

    tableView.reloadData()

}

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return checklists.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "ChecklistCell", for: indexPath) as! ListsTableViewCell

    cell.name.text = checklists[indexPath.row].name
    return cell
}

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {

        // Delete the row from the data source
        try! realm.write {
            realm.delete(checklists[indexPath.row])
        }

        //delete locally
        checklists.remove(at: indexPath.row)

        self.tableView.deleteRows(at: [indexPath], with: .fade)
    }
}

我知道这部分是具体的:

     // Delete the row from the data source
        try! realm.write {
            realm.delete(checklists[indexPath.row])
        }

关于发生了什么的任何想法? 提前谢谢!

2 个答案:

答案 0 :(得分:16)

您正在尝试删除存储在集合中的Realm对象的副本,而不是存储在Realm中的实际Realm对象。

try! realm.write {
    realm.delete(Realm.objects(ChecklistDataModel.self).filter("name=%@",checklists[indexPath.row].name))
}

如果没有CheklistDataModel的定义,我不确定我是否正确使用NSPredicate,但你应该能够从这里找到它。

答案 1 :(得分:1)

从您分享的代码段中,您似乎正在创建新的ChecklistDataModel对象,但从未将它们添加到任何Realm。然后,您尝试在try! realm.write块中删除Realm中的这些对象。

简单地实例化一个对象并不意味着它已被添加到一个领域;直到它通过成功的写入事务添加到Realm,它的行为就像任何其他Swift实例一样。只有在将对象添加到Realm后,才能成功将其从同一个Realm中删除。