为什么即使代码已经在realm.write内,我还是出现错误“试图在写事务之外修改对象”?

时间:2018-11-27 10:54:24

标签: ios swift realm

我正在尝试使用领域保存数据,以将喜欢的产品保存到愿望清单

enter image description here

所以我以一对多关系创建了两个对象WishListProducts

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
        }

从下面的代码(从上面的代码)中删除“愿望清单产品列表”中的产品时遇到问题

// 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 {}内部,但出现错误:

  

'试图在写事务之外修改对象-调用   首先在RLMRealm实例上执行beginWriteTransaction。'

说实话,我对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()

    }

这里出了什么问题?

0 个答案:

没有答案