我試圖設計一個按鈕,允許用戶「保存」集合視圖表上的列表。當按鈕被觸摸時,列表的數據被保存到領域,另一個視圖控制器呈現這些數據。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)")
}
我明白,我需要的數據加載與保存布爾堅持,但我不明白爲什麼它贏得了」讓我第三次點擊。
你能發表更多的代碼嗎?因爲我有點混淆像'lib.Library [indexPath.item] .saved'這樣的多個變量。等等順便說一句,你可以張貼幾個截圖,會很高興有一個清晰的想法 –
@PangHoMing編輯它使它更清晰一點,對於亂碼(對於後來刪除它,因爲有另一個組件,我不得不添加。) –