Я пытаюсь сохранить данные, используя область, чтобы сохранить понравившийся товар в списке желаний
, поэтому я делаю два объекта, WishList
итакже Products
в отношении один ко многим
class WishList : Object {
@objc dynamic var userID: String = ""
var products = List<Product>()
}
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")
var totalPrice : Double {
return Double(quantity) * unitPrice
}
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
}
}
метод, который срабатывает, когда эта кнопка любви нажата, находится в приведенном ниже коде.
var userWishList : WishList?
let realm = try! Realm()
private var products = [Product]() // will be populated by data from server
func loveButtonDidTapped(at selectedIndexPath: IndexPath, loveButtonHasBeenFilled: Bool) {
let selectedProduct = products[selectedIndexPath.item]
// update the product data on the array (product list), update the status whether the product has been added to wishlist or not
selectedProduct.hasBeenAddedToWishList = loveButtonHasBeenFilled
collectionView.reloadData()
var theWishList = WishList()
if let userWishList = userWishList {
theWishList = userWishList
} else {
let userID = "1"
let newWishList = WishList()
newWishList.userID = userID
newWishList.products = List<Product>()
userWishList = newWishList
theWishList = newWishList
do {
try self.realm.write {
realm.add(newWishList)
}
} catch {
showAlert(alertTitle: "Sorry", alertMessage: error.localizedDescription, actionTitle: "Back")
}
}
// add or remove product in Realm Database
if loveButtonHasBeenFilled {
// save to Realm Database
do {
try self.realm.write {
theWishList.products.append(selectedProduct)
let allWishList = realm.objects(WishList.self)
userWishList = allWishList.filter("userID CONTAINS[cd] %@", "1").first!
}
} catch {
showAlert(alertTitle: "Sorry", alertMessage: error.localizedDescription, actionTitle: "Back")
}
} else {
// delete from realm database
do {
try realm.write {
guard let index = theWishList.products.index(where: {$0.productID == selectedProduct.productID}) else {return}
theWishList.products.remove(at: index)
}
} catch {
showAlert(alertTitle: "Sorry", alertMessage: error.localizedDescription, actionTitle: "Back")
}
}
}
userWishList
определяется этимкод
let allWishList = realm.objects(WishList.self)
if !allWishList.isEmpty {
// filter based on user ID
userWishList = allWishList.filter("userID CONTAINS[cd] %@", userID).first
}
У меня возникла проблема при удалении продукта из «Списка продуктов WishList», в приведенном ниже коде (из кода выше)
// delete from realm database
do {
try realm.write {
guard let index = theWishList.products.index(where: {$0.productID == selectedProduct.productID}) else {return}
theWishList.products.remove(at: index)
}
ясно, что remove
находится внутри realm.write {}
, но появляется сообщение об ошибке:
'Попытка изменить объект вне транзакции записи - сначала вызовите beginWriteTransaction для экземпляра RLMRealm.'
Если честно, я не совсем понимаю, с beginWriteTransaction
, это то же самое, что realm.write {}
???
, когда приложение загружается впервые, я могу удалить продукт из списка желаний без сбоев, но после того, как я нажму кнопку любви, чтобы снова поместить товар в список желаний, а затем удалитьопять же, при втором удалении произойдет сбой с сообщением об ошибке, как указано выше.вот видео / gif моей проблемы
http://recordit.co/3bCydOuE38
http://g.recordit.co/3bCydOuE38.gif
вот начальная установка в viewDidLoad, чтобы дать значок заполненной любви дляпродукт, который уже был в WishList ранее, поэтому продукт, который уже есть в WishList, будет отображаться с иконкой заполненной любви.
var userWishList : WishList?
private func setUpFilledLovedIconProduct() {
// if the product has been added to wishlist before then give filled love icon.
// get the WishList products that match the userID
guard let wishListedProducts = userWishList?.products else {return}
// set the property 'hasBeenAddedToWishList' accordingly
let wishListedIds = wishListedProducts.map {$0.productID}
for product in products {
if wishListedIds.contains(product.productID) {
product.hasBeenAddedToWishList = true
}
}
collectionView.reloadData()
}
что здесь не так?