如何在Swift中删除领域对象

时间:2019-04-05 03:53:53

标签: ios swift realm

我检查了许多其他答案,但是在删除领域数据表数据库时仍然存在问题。 这是我的错误代码:

  

由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'-[[Rebel.RebelTableViewController delete:]:无法识别的选择器发送到实例0x7fca7b40b5c0

此代码是从我的表格视图中删除的:

if editingStyle == UITableViewCellEditingStyle.delete {
    rowHere = indexPath.row
    // it crashes the app when I want to delete from database

    //  delete(self.todos[self.rowHere!])

    self.Rebel.remove(at: indexPath.row)
    tableView.deleteRows(at: [indexPath as IndexPath], with: UITableViewRowAnimation.automatic)
}

1 个答案:

答案 0 :(得分:0)

Object中首先获得viewDidLoad()模型

var DatabaseModel: Results<ObjectClassRealm>!

override func viewDidLoad() {
    super.viewDidLoad()
    let realm = RealmService.shared.realm
    DatabaseModel = realm.objects(ObjectClassRealm.self)
}




func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 
    guard editingStyle == .delete else { return }
    let objectData = DatabaseModel[indexPath.row]
    RealmService.shared.delete(objectData)
}

或者您也可以单击按钮删除

@IBAction func DeleteData(_ sender: Any) {
    let realm = try! Realm()
    let deleteData = realm.object(ofType: ObjectClassRealm.self, 
                                  forPrimaryKey: PRIMARYKEY)
    if deleteData == nil {
        print("No data in DB")
    } else {
        RealmService.shared.delete(deleteData!)
    }
}

阅读领域文档,您还将找到许多解决同一问题的方法。