加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 02:28:55 所属栏目:百科 来源:网络整理
导读:我每次尝试从我的tableview上的域中删除一个对象时,我都会收到此错误“只能从它所属的域中删除一个对象”.这是相关代码: let realm = try! Realm()var checklists = [ChecklistDataModel]()override func viewWillAppear(_ animated: Bool) { checklists =
我每次尝试从我的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])
        }

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

您正在尝试删除存储在集合中的Realm对象的副本,而不是存储在Realm中的实际Realm对象.
try! realm.write {
    realm.delete(Realm.objects(ChecklistDataModel.self).filter("name=%@",checklists[indexPath.row].name))
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读