从realm数据库中删除对象。

时间:2017-06-07 19:31:24

标签: swift realm

我正在写Todo app。我的应用很简单。我有两页。一个用于在表视图中显示任务的页面。还有一个用于添加新任务的页面。在这个页面中,我发布到服务器,然后在主页面中,我从服务器获取数据,然后将其保存在realm数据库中。

当我想在我的主页面中删除它们时,我的应用程序因此错误而崩溃。

DOMXpath

任何人都知道为什么? 这是我的删除功能:

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

4 个答案:

答案 0 :(得分:2)

我在我的应用程序中实现了类似的功能,希望它对您有所帮助。

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

I'm thinking that the error message is deceiving. You haven't shown where you define the class property rowHere (as an integer), but the variable isn't needed here.

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

if todos is an array of your realm Object subclass, then this should work:

   let objectToDelete = self.todos[indexPath.row]
   delete(objectToDelete])

as long as your delete is something like this: (my Realm instance is called realmStore)

func delete(objectToDelete: Object) // use your subclass name
    do {
       try realmStore.write {
          realmStore.delete(record)
       }
    } catch {
       print("Could not delete object.\n\(String(describing: error.localizedDescription))"
}

答案 3 :(得分:0)

我发现这个问题来自&#34;删除&#34;字。似乎这个词保留给Xcode。当我调用它时,它会转到另一个不是我的地方的删除方法。我将名称更改为例如deleteSomethings并且它有效。