我试图设计一个按钮,允许用户“保存”集合视图表上的列表。当按钮被触摸时,列表的数据被保存到领域,另一个视图控制器呈现这些数据。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编辑它使它更清晰一点,对于乱码(对于后来删除它,因为有另一个组件,我不得不添加。) –