首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >只能从它所属的领域中删除对象。

只能从它所属的领域中删除对象。
EN

Stack Overflow用户
提问于 2017-05-09 04:01:26
回答 2查看 11K关注 0票数 16

每当我尝试从我的表视图中的领域中删除一个对象时,我都会收到这个错误“只能从它属于的领域中删除一个对象”。以下是相关代码:

代码语言:javascript
运行
复制
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)
    }
}

我知道这部分是具体的:

代码语言:javascript
运行
复制
     // Delete the row from the data source
        try! realm.write {
            realm.delete(checklists[indexPath.row])
        }

对发生了什么事有什么想法吗?提前感谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-05-09 08:43:50

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

代码语言:javascript
运行
复制
try! realm.write {
    realm.delete(Realm.objects(ChecklistDataModel.self).filter("name=%@",checklists[indexPath.row].name))
}

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

票数 32
EN

Stack Overflow用户

发布于 2017-05-09 18:48:36

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

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43860885

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档