像下面的代码一样,Product
和WishList
这两个模型之间存在一对多的关系
class Product : Object {
@objc dynamic var productID : String = ""
@objc dynamic var name : String = ""
@objc dynamic var unitPrice: Double = 0.0
@objc dynamic var imagePath : String = ""
@objc dynamic var quantity = 0
@objc dynamic var hasBeenAddedToWishList : Bool = false
var parentCategory = LinkingObjects(fromType: WishList.self, property: "products")
convenience init(productID : String, name: String, unitPrice: Double, imagePath: String, quantity: Int = 1, hasBeenAddedToWishList: Bool = false) {
self.init()
self.productID = productID
self.name = name
self.unitPrice = unitPrice
self.imagePath = imagePath
self.quantity = quantity
self.hasBeenAddedToWishList = hasBeenAddedToWishList
}
override static func primaryKey() -> String? {
return "productID"
}
}
和愿望清单:
class WishList : Object {
@objc dynamic var userID: String = ""
var products = List<Product>()
}
当我按下上图中的“爱”按钮时,我尝试使用以下代码将产品添加或删除到愿望清单:
// 1. get the wishlist based on UserID
let allWishList = realm.objects(WishList.self)
let theWishList = allWishList.filter("userID CONTAINS[cd] %@", userID).first
guard let userWishList = theWishList else {return}
// 2. modify Wishlist data in Realm.
if loveIconHasBeenFilled {
guard let index = userWishList.products.index(where: {$0.productID == selectedProduct.productID}) else {return}
do {
// remove data from realm database
try realm.write {
userWishList.products.remove(at: index)
}
} catch {
// error Handling
}
} else {
do {
// add product to wishlist model in realm database
try realm.write {
userWishList.products.append(selectedProduct)
}
} catch {
// error Handling
}
}
问题出在....
当我第一次运行该应用程序时,我可以添加,然后删除,然后将产品再次添加到心愿单,并且领域数据库中的产品数量仍然相同(都具有唯一的productID)
但是当我重新启动应用程序,并尝试单击该“爱”按钮再次将产品添加到愿望清单时,它会引发错误
“ RLMException”,原因:“试图创建类型的对象 现有主键值为“ a”的“产品”
由于此行代码userWishList.products.append(selectedProduct)
触发了此错误,当将产品添加到WishList
时,它会自动将Product
添加到领域数据库中。因此,由于我不断添加具有相同productID(主键)的同一产品,因此会抛出该错误。
所以,我的问题是,如果它具有相同的productID(主键),如何避免在Product
中添加,最好在将产品添加到愿望清单时更新领域数据库中的产品使用以下代码行:userWishList.products.append(selectedProduct)
答案 0 :(得分:0)
您可以检查所选产品的属性hasBeenAddedToWishList
,只有在该属性为false时才能添加。
if loveIconHasBeenFilled {
//your logic to remove already added products
} else if !selectedProduct.hasBeenAddedToWishList { //<--- check if the product already exists in wishlist if not you add it
do {
// add product to wishlist model in realm database
try realm.write {
userWishList.products.append(selectedProduct)
}
} catch {
// error Handling
}
}