【问题标题】:Can only delete an object from the Realm it belongs to只能从它所属的 Realm 中删除一个对象
【发布时间】:2017-05-09 04:01:26
【问题描述】:

每次我尝试从我的 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])
        }

对正在发生的事情有任何想法吗? 提前致谢!

【问题讨论】:

    标签: swift uitableview realm


    【解决方案1】:

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

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

    如果没有 CheklistDataModel 的定义,我不确定我的 NSPredicate 是否正确,但您应该可以从这里弄清楚。

    【讨论】:

      【解决方案2】:

      从您共享的代码 sn-ps 来看,您似乎正在创建新的 ChecklistDataModel 对象,但从未将它们添加到任何领域。然后,您尝试在 try! realm.write 块中从您的领域中删除这些对象。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-12
        • 1970-01-01
        • 2016-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-23
        • 1970-01-01
        相关资源
        最近更新 更多