简体   繁体   中英

How to delete object in realm in Swift

I check many other answers but still having problem with deleting data form database of realm. This is my error code :

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Rebel.RebelTableViewController delete:]: unrecognized selector sent to instance 0x7fca7b40b5c0

This code is from my table view to delete:

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)
}

First get Object model in 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)
}

Or you can delete on button click

@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!)
    }
}

read documents of realm, also you will find many solutions for same question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM