title: Object isn't updating in tableview with new Realm data
body: <p>Whenever I click on a row in my tableview and change the text in the fields to something else, it always crashes and doesn't actually update the data. I'm saving all my data in a "Realm" database, which im fairly new at using. </p>
  
  <p>I'm doing the updating in the "unwindToNoteList" function. Can someone help me know why it's adding a new row and crashing instead of updating the current row?</p>
  
  <pre><code>import UIKit
  import Realm
  
  class NoteTableViewController: UITableViewController {
  
      // MARK: Properties
  
      var notes = Note.allObjects()
  
      override func viewDidLoad() {
          super.viewDidLoad()
  
          // Get Realm Database location
          println(RLMRealm.defaultRealm().path)
      }
  
      override func didReceiveMemoryWarning() {
          super.didReceiveMemoryWarning()
          // Dispose of any resources that can be recreated.
      }
  
      // MARK: - Table view data source
  
      override func numberOfSectionsInTableView(tableView: UITableView) -&gt; Int {
          // Return the number of sections.
          return 1
      }
  
      override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {
          // Return the number of rows in the section.
          return Int(notes.count)
      }
  
  
      override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell {
          // Table view cells are reused and should be dequeued using a cell identifier.
          let cellIdentifier = "NoteTableViewCell"
          let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! NoteTableViewCell
  
          let object = notes[UInt(indexPath.row)] as! Note
  
          // Configure the cell...
          cell.titleLabel.text = object.title
          cell.bodyLabel.text = object.body
  
          return cell
      }
  
      // Override to support conditional editing of the table view.
      override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -&gt; Bool {
          // Return NO if you do not want the specified item to be editable.
          return true
      }
  
      // Override to support editing the table view.
      override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
          if editingStyle == .Delete {
  
              // Delete from database
              let realm = RLMRealm.defaultRealm()
              realm.beginWriteTransaction()
              realm.deleteObject(notes[UInt(indexPath.row)] as! RLMObject)
              realm.commitWriteTransaction()
  
              // Delete row from table view
              tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
          } else if editingStyle == .Insert {
              // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
          }
      }
  
      // MARK: - Navigation
  
      // In a storyboard-based application, you will often want to do a little preparation before navigation
      override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
          if segue.identifier == "ShowDetail" { // Clicked on a cell
              let noteDetailViewController = segue.destinationViewController as! NoteViewController
              // Get the cell that generated this segue.
              if let selectedNoteCell = sender as? NoteTableViewCell {
                  let indexPath = tableView.indexPathForCell(selectedNoteCell)!
  
                  let selectedNote = notes[UInt(indexPath.row)] as! Note
                  noteDetailViewController.note = selectedNote
  
              }
          }
          else if segue.identifier == "AddItem" { // Clicked add button
              println("Adding new note")
          }
      }
  
      @IBAction func unwindToNoteList(sender: UIStoryboardSegue) {
                 if let selectedIndexPath = tableView.indexPathForSelectedRow() { // User clicked on a row
  
              // Update an existing note.
              let realm = RLMRealm.defaultRealm()
              realm.beginWriteTransaction()
  
              Note.createOrUpdateInRealm(realm, withValue: ["title": note.title, "body": note.body, "id": note.id])
              realm.commitWriteTransaction()
  
              println("Yes")
  
              tableView.reloadRowsAtIndexPaths([selectedIndexPath], withRowAnimation: .None)
          }
          else {
              // Add a new note.
              let newIndexPath = NSIndexPath(forRow: Int(notes.count), inSection: 0)
  
              // Persist in database
              let realm = RLMRealm.defaultRealm()
              realm.beginWriteTransaction()
              Note.createInRealm(realm, withValue: ["title": note.title, "body": note.body, "id": uuid])
              realm.commitWriteTransaction()
  
              println("no")
  
              tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom)
          }
          }
      }
  
  }
  </code></pre>
  
  <p><strong>Finally solved this, by not updating the object while in the tableview but while in the view controller that holds the text fields</strong></p>
  
  <p>Here's my NoteViewController</p>
  
  <pre><code>import UIKit
  import Realm
  
  class NoteViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
  
      // MARK: Properties
  
      @IBOutlet var saveButton: UIBarButtonItem!
      @IBOutlet var titleTextField: UITextField!
      @IBOutlet var bodyTextField: UITextField!
  
      /*
      This value is either passed by `NoteTableViewController` in `prepareForSegue(_:sender:)`
      or constructed as part of adding a new note.
      */
      var note = Note?()
  
      // MARK: Navigation
  
      @IBAction func cancel(sender: UIBarButtonItem) {
          // Depending on style of presentation (modal or push presentation), this view controller needs to be dismissed in two different ways.
          let isPresentingInAddNoteMode = presentingViewController is UINavigationController
          if isPresentingInAddNoteMode {
              dismissViewControllerAnimated(true, completion: nil)
          } else {
              navigationController!.popViewControllerAnimated(true)
          }
      }
  
      // This method lets you configure a view controller before it's presented.
      override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
          if saveButton === sender {
              let title = titleTextField.text ?? ""
              let body = bodyTextField.text ?? ""
  
              /* The operator ?? unwraps the optional string in titleTextField.text since it may or may not have text in the field, and returns the value if it's a valid string. If nil though, it returns and empty string ("") instead
              */
  
              // Update the database
              let realm = RLMRealm.defaultRealm()
              realm.beginWriteTransaction()
  
              note?.title = titleTextField.text
              note?.body = bodyTextField.text
  
              realm.commitWriteTransaction()
  
              // Set the note to be passed to NoteTableViewController after the unwind segue.
              // AKA pass "note" to NoteTableViewController with whatever the text fields have in them
              note = Note(title: title, body: body)
          }
  
      }
  
      override func viewDidLoad() {
          super.viewDidLoad()
          // Do any additional setup after loading the view, typically from a nib.
  
          // Handle the text field’s user input through delegate callbacks.
          titleTextField.delegate = self
  
          // Set up views if editing an existing Note.
          if let note = note {
              navigationItem.title = note.title
              titleTextField.text = note.title
              bodyTextField.text = note.body
          }
  
          // Enable the Save button only if the text field has a valid Note name.
          checkValidNoteName()
      }
  
      override func didReceiveMemoryWarning() {
          super.didReceiveMemoryWarning()
          // Dispose of any resources that can be recreated.
      }
  
      // MARK: UITextFieldDelegate
  
      func textFieldDidBeginEditing(textField: UITextField) {
          // Disable the Save button while editing.
          saveButton.enabled = false
      }
  
      func checkValidNoteName() {
          // Disable the Save button if the text field is empty.
          let text = titleTextField.text ?? ""
          saveButton.enabled = !text.isEmpty
      }
  
      func textFieldDidEndEditing(textField: UITextField) {
          checkValidNoteName()
          navigationItem.title = textField.text
      }
  
  
  }
  </code></pre>
  
  <p>And here's the original, NoteTableViewController. Updated a bit as well.</p>
  
  <pre><code>import UIKit
  import Realm
  
  class NoteTableViewController: UITableViewController {
  
    // MARK: Properties
  
      var notes = Note.allObjects()
  
      override func viewDidLoad() {
          super.viewDidLoad()
  
          // Get Realm Database location
          println(RLMRealm.defaultRealm().path)
  
      }
      override func didReceiveMemoryWarning() {
          super.didReceiveMemoryWarning()
          // Dispose of any resources that can be recreated.
      }
  
      // MARK: - Table view data source
  
      override func numberOfSectionsInTableView(tableView: UITableView) -&gt; Int {
          // Return the number of sections.
          return 1
      }
  
      override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {
          // Return the number of rows in the section.
          return Int(notes.count)
      }
  
  
      override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell {
          // Table view cells are reused and should be dequeued using a cell identifier.
          let cellIdentifier = "NoteTableViewCell"
          let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! NoteTableViewCell
  
          let object = notes[UInt(indexPath.row)] as! Note
  
          // Configure the cell...
          cell.titleLabel.text = object.title
          cell.bodyLabel.text = object.body
  
          return cell
      }
  
      // Override to support conditional editing of the table view.
      override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -&gt; Bool {
          // Return NO if you do not want the specified item to be editable.
          return true
      }
  
      // Override to support editing the table view.
      override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
          if editingStyle == .Delete {
  
              // Delete from database
              let realm = RLMRealm.defaultRealm()
              realm.beginWriteTransaction()
              realm.deleteObject(notes[UInt(indexPath.row)] as! RLMObject)
              realm.commitWriteTransaction()
  
              // Delete row from table view
              tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
          } else if editingStyle == .Insert {
              // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
          }
      }
  
      // MARK: - Navigation
  
      // In a storyboard-based application, you will often want to do a little preparation before navigation
      override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
          if segue.identifier == "ShowDetail" { // Clicked on a cell
              let noteDetailViewController = segue.destinationViewController as! NoteViewController
              // Get the cell that generated this segue.
              if let selectedNoteCell = sender as? NoteTableViewCell {
                  let indexPath = tableView.indexPathForCell(selectedNoteCell)!
  
                  let selectedNote = notes[UInt(indexPath.row)] as! Note
                  noteDetailViewController.note = selectedNote
  
              }
          }
          else if segue.identifier == "AddItem" { // Clicked add button
              println("Adding new note")
          }
      }
  
      @IBAction func unwindToNoteList(sender: UIStoryboardSegue) {
          if let sourceViewController = sender.sourceViewController as? NoteViewController, note = sourceViewController.note {
  
              let uuid = NSUUID().UUIDString // Needed for primary key. see below
  
              var unwindedNote = Note()
  
              if let selectedIndexPath = tableView.indexPathForSelectedRow() { // User clicked on a row
  
                  // Updating of the note is done in NoteViewController
  
                  tableView.reloadRowsAtIndexPaths([selectedIndexPath], withRowAnimation: .None)
              }
              else {
                  // Add a new note.
                  let newIndexPath = NSIndexPath(forRow: Int(notes.count), inSection: 0)
  
                  // Persist in database
                  let realm = RLMRealm.defaultRealm()
                  realm.beginWriteTransaction()
  
                  unwindedNote.title = note.title
                  unwindedNote.body = note.body
                  unwindedNote.id = uuid // This is done for the primary key that Realm needs, unique for each object created.
  
                  realm.addObjects([unwindedNote])
                  realm.commitWriteTransaction()
  
                  tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom)
              }
          }
      }
  }
  </code></pre>