title: RealmSwift "Object has been deleted or invalidated"
body: <p>I'm trying to design a button that allows users to "save" a listing on a collection view table. When the button is touched the listing's data is saved to realm and another view controller presents this data.</p>
  
  <p>While I am able to get the data to persist onto Realm and show up and remove it if I tap the button again if I tap it the third time I get "Object has been deleted or invalidated", even if it's a different listing. Here's the code to give some insight into what I'm trying to do: </p>
  
  <pre><code>let lib = BookCollection()
  
  let realm = try! Realm()
  
  var unSavedBook = RealmBook()
  
  func save(_ cell: HomeBookPreviewViewCell) {
  
      // This allows me to get the indexpath of a cell to use buttons on the collection view.
  
      guard let indexPath = self.bookListing.indexPath(for: cell) else {
          print("whaaaaaaa")
          return
      }
  
  
      if lib.Library[indexPath.item].saved {
  
          let savedBooks = realm.object(ofType: RealmBook.self, forPrimaryKey: lib.Library[indexPath.item].isbn!)
           try! realm.write {
  
  
  
              realm.delete(savedBooks!)
  
              //updates other view controller
  
              NotificationCenter.default.post(name: .reload, object: nil)
          }
  
          cell.saveButton.setImage(#imageLiteral(resourceName: "Star"), for: .normal)
          lib.Library[indexPath.item].saveBook(save: false)
      }
      else if (!lib.Library[indexPath.item].saved) {
  
          try! realm.write {
          //unSavedBooks is declared outside of function.
  
          //lib.Libary is an object that holds an array of Book objects with book attributes.
  
          unSavedBook.addRealmBook(lib.Library[indexPath.item].title!, lib.Library[indexPath.item].author!, lib.Library[indexPath.item].edition!, lib.Library[indexPath.item].publisher!, "\(lib.Library[indexPath.item].type!)", "\(lib.Library[indexPath.item].condition!)", "\(lib.Library[indexPath.item].subject!)", lib.Library[indexPath.item].seller!, RealmOptional&lt;Float&gt;(lib.Library[indexPath.item].price), lib.Library[indexPath.item].isbn!)
  
              realm.add(unSavedBook)
  
              //updates other view controller
              NotificationCenter.default.post(name: .reload, object: nil)
  
          }
  
  
  
  
          cell.saveButton.setImage(#imageLiteral(resourceName: "Star-Saved"), for: .normal)
  
          lib.Library[indexPath.item].saveBook(save: true)
      }
      print("Button tapped on row \(indexPath.item)")
  }
  </code></pre>
  
  <p>I understand that I need to make the data load in with the saved boolean persisted, but i don't understand why it won't allow me to click for the third time.</p>