Reputation: 21
I am deleting a Realm object and am getting this error:
Terminating app due to uncaught exception 'RLMException', reason: 'Can only add, remove, or create objects in a Realm in a write transaction - call beginWriteTransaction on an RLMRealm instance first.'
I have tried refresh()
extension Realm {
func addWord(_ word: RelatedWord) {
do {
try self.write {
self.add(word)
}
} catch let error {
print(error.localizedDescription)
}
}
func deleteWord(_ word: RelatedWord) {
BG {
do {
self.beginWrite()
self.delete(word)
try self.commitWrite()
//self.refresh()
} catch let error {
print(error.localizedDescription)
}
self.refresh()
}
}
}
VC:
realm.delete(word)
Expected result: swipe to delete object from tableview
Error: object deletion not being hnadled properly.
*** Terminating app due to uncaught exception 'RLMException', reason: 'Can only add, remove, or create objects in a Realm in a write transaction - call beginWriteTransaction on an RLMRealm instance first.'
I think the issue is not with my function to delete a realm object but rather that there is an inconsistency between the Realm objects and the table view attempting to access deleted objects.
// Swipe to delete cell and word
func tableView(_ tableView: UITableView,trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let action = UIContextualAction(style: .normal, title: "Delete", handler: { (action, view, completionHandler) in
// Update data source when user taps action
let letters = DataSingleton.shared.relatedArr.keys.sorted()
if let data = DataSingleton.shared.relatedArr[letters[indexPath.section]]?.sorted(by: {$0.word < $1.word}) {
let word = data[indexPath.row]
print(word.word)
self.realm.delete(word)
tableView.beginUpdates()
tableView.deleteRows(at: [indexPath], with: .fade)
tableView.reloadRows(at: [indexPath], with: .automatic)
tableView.endUpdates()
}
completionHandler(true)
})
Upvotes: 1
Views: 964
Reputation: 1630
I'm not sure what BG is, but I would do it like this instead:
func deleteWord(_ word: RelatedWord) {
do {
try self.write {
self.delete(word)
}
} catch let error {
print(error.localizedDescription)
}
self.refresh()
}
Upvotes: 0