每当我尝试从我的表视图中的领域中删除一个对象时,我都会收到这个错误“只能从它属于的领域中删除一个对象”。以下是相关代码:
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])
}
对发生了什么事有什么想法吗?提前感谢!
发布于 2017-05-09 08:43:50
您正在尝试删除存储在集合中的领域对象的副本,而不是存储在领域中的实际领域对象的副本。
try! realm.write {
realm.delete(Realm.objects(ChecklistDataModel.self).filter("name=%@",checklists[indexPath.row].name))
}
如果没有CheklistDataModel的定义,我不确定我是否正确地使用了NSPredicate,但是您应该能够从这里找到它。
发布于 2017-05-09 18:48:36
从您共享的代码片段中,您似乎正在创建新的ChecklistDataModel
对象,但从未将它们添加到任何领域。然后尝试从try! realm.write
块中的领域中删除这些对象。
简单地实例化一个对象并不意味着它已经被添加到一个领域;直到它通过一个成功的写事务添加到一个领域,它的行为就像任何其他Swift实例一样。只有在将对象添加到一个领域之后,才能成功地从同一领域中删除它。
https://stackoverflow.com/questions/43860885
复制相似问题