只能从其所属领域删除对象 [英] Can only delete an object from the Realm it belongs to

查看:85
本文介绍了只能从其所属领域删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次尝试从表视图的领域中删除对象时,都会出现此错误"只能从其所属领域删除对象".这是相关代码:

Im getting this error "Can only delete an object from the Realm it belongs to" every time I try to delete an object from realm on my tableview. Here is the relevant code:

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)
    }
}

我知道这是要具体的部分:

I know it is this part to be specific:

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

有什么想法吗? 预先感谢!

Any ideas of what is going on? Thanks in advance!

推荐答案

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

You are trying to delete copies of your Realm objects stored in a collection instead of your actual Realm objects stored in Realm.

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

没有CheklistDataModel的定义,我不确定我是否正确使用了NSPredicate,但是您应该可以从这里弄清楚.

Without the definition of CheklistDataModel, I am not sure if I got the NSPredicate right, but you should be able to figure it out from here.

这篇关于只能从其所属领域删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆