2017-03-07 81 views
0

我試圖設計一個按鈕,允許用戶「保存」集合視圖表上的列表。當按鈕被觸摸時,列表的數據被保存到領域,另一個視圖控制器呈現這些數據。RealmSwift「對象已被刪除或無效」

雖然我能夠讓數據堅持到領域並顯示並刪除它,如果我再次點擊按鈕,如果我點擊它第三次我得到「對象已被刪除或無效」,即使它是一個不同的上市。下面的代碼給一些洞察到我想要做的事:

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

我明白,我需要的數據加載與保存布爾堅持,但我不明白爲什麼它贏得了」讓我第三次點擊。

+0

你能發表更多的代碼嗎?因爲我有點混淆像'lib.Library [indexPath.item] .saved'這樣的多個變量。等等順便說一句,你可以張貼幾個截圖,會很高興有一個清晰的想法 –

+1

@PangHoMing編輯它使它更清晰一點,對於亂碼(對於後來刪除它,因爲有另一個組件,我不得不添加。) –

回答

0

當您嘗試讀取最有可能已被刪除的領域對象的屬性時,您會看到此異常。請確保您沒有任何強引用刪除的領域對象,或嘗試使用isInvalidated屬性來處理這種情況。

0

我以前在開發iOS時使用CoreData + Magical記錄。只有當我開發Android應用程序時才能使用Realm。

夫婦的問題,

  1. 像CoreData /等現代數據庫,結果你獲取來自境界查詢是自動更新。 (Ref:https://realm.io/docs/swift/latest/#auto-updating-results)。所以,我對你的NotificationCenter.default.post(name: .reload, object: nil)電話有些困惑。另外,你能向我們展示你的Collection View數據源委託方法的實現嗎?因爲那裏包括一些Realm電話。
  2. 第二個問題是關於你的應用程序流。從我的理解中,有一個Collection View,每個單元顯示一個Book。如果單擊單元格Book,則會顯示另一個視圖來顯示書籍信息。如果第二次點擊它,則刪除該書。但如果該書被刪除,第三次如何使用可以點擊該單元格?您是否期望Book單元格被刪除?張貼一對夫婦截圖將是很好的,我們可以幫助你:)
相關問題