简体   繁体   中英

How to update existing value on realm database swift?

I want to make any row from 'false' to 'true' or vice versa depending on table view did select and did deselect method. That mean's I need to update the existing value. How to do that. My code is not working it's creating another row instead of updating the existing one.

Here is the table

.

Here is the model

import UIKit
import RealmSwift

class TodoData: Object {

    @objc dynamic var todos: String = String()
    @objc dynamic var times: String = String()
    @objc dynamic var rows: Bool = Bool()

}

Here is the code I wrote for updating the value of the existing row:

    let data = TodoData()

            do {
                try realm.write {
                    data.rows = true
                    realm.add(data)
                }
            } catch let error as NSError {
                print(error.localizedDescription)
            }

Your code is not updating existing data. It is creating a new ToDoData and inserting it.

You want to fetch an existing ToDoData and update in write . Here is an example.

let todos = "a"
guard let data = realm.objects(ToDoData.self).filter("todos == %@", todos).first else { return }
try! realm.write {
    data.rows = true
}

If you literaly want to:

I want to make any row from 'false' to 'true' or vice versa

Here's the code that will make all false rows true, and all true row false.

let toDoResults = realm.objects(TodoData.self)
for toDo in toDoResults {
    try! realm.write {
        toDo.rows = !toDo.rows
    }
}

I think though, you just want to toggle a row when the user makes a change in your tableView.

let selectedTodo = "a"
let results = realm.objects(TodoData.self).filter("todos == %@", selectedTodo)
if let thisTodo = results.first {
   try! realm.write {
      thisTodo.rows = !thisTodo.rows //will toggle from t to f and from f to t
   }
}

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