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

Noa*_*h-1 7 realm uitableview swift

我每次尝试从我的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)
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道这部分是具体的:

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

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

Dáv*_*tor 19

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

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

如果没有CheklistDataModel的定义,我不确定我是否正确使用NSPredicate,但你应该能够从这里弄明白.