我正在编写 Todo 应用程序。我的应用程序很简单。我有两页。用于在表格 View 中显示任务的一页。还有一页用于添加新任务。在此页面中,我发布到服务器,然后在主页面中,我从服务器获取数据,然后将其保存在 Realm 数据库中。
当我想在我的主页中删除它们时,我的应用程序因这个错误而崩溃。
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[TodoApp.TodosTableViewController delete:]: unrecognized selector sent to instance 0x7fca7b40b4c0
谁知道为什么? 这是我的删除功能:
public func delete<T:Object>(_ model: T) {
let realm = try! Realm()
try! realm.write {
realm.delete(model)
}
}
这是我使用这个函数从数据库中删除的地方:
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath){
if editingStyle == UITableViewCellEditingStyle.delete {
rowHere = indexPath.row
// it crashes the app when I want to delete from database
// delete(self.todos[self.rowHere!])
self.todos.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath as IndexPath], with: UITableViewRowAnimation.automatic)
}
}
最佳答案
我在我的应用中实现了类似的东西,希望它对你有帮助。
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
//deleteRecords()
delete(index: indexPath.row)
retrieveFoods()
tableView.reloadData()
}
func retrieveFoods() {
let realm = try! Realm()
myFoodsArray = realm.objects(MyFoods.self).sorted(byKeyPath: "name", ascending: true)
}
func delete(index: Int) {
let myFood = myFoodsArray[index]
let realm = try! Realm()
try! realm.write {
realm.delete(myFood)
self.tableView.reloadData()
}
}
关于swift - 从 Realm 数据库中删除对象。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44421325/