ios - 如何避免在 Realm 数据库中添加具有相同主键的相同数据模型?

标签 ios swift realm

enter image description here

我在两个模型之间有一对多关系,ProductWishList 如下面的代码

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>()
}

当按下上图中的爱心按钮时,我尝试使用下面的代码将产品添加或删除到愿望 list :

    // 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
      }


   }

这是 Realm 浏览器中的数据 enter image description here

enter image description here

问题是....

当我第一次运行应用程序时,我可以添加,然后删除,然后再次将产品添加到愿望 list ,并且 Realm 数据库中的产品数量仍然相同(都有唯一的产品ID)

但是当我重新启动应用程序并尝试再次单击那个爱心按钮将产品添加到愿望 list 时,它会抛出错误

'RLMException', reason: 'Attempting to create an object of type 'Product' with an existing primary key value 'a'

这个错误是因为这行代码 userWishList.products.append(selectedProduct) 触发的,当添加产品到 WishList 时,它会自动添加 Product 在 Realm 数据库中。因此,因为我不断添加具有相同产品 ID(主键)的相同产品,所以会抛出该错误。

所以,我的问题是,如果 Product 具有相同的 productID(主键),如何避免添加,最好在添加产品时只更新 Realm 数据库中的产品使用这行代码添加到心愿单:userWishList.products.append(selectedProduct)

最佳答案

您可以检查所选产品的属性 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
  }

关于ios - 如何避免在 Realm 数据库中添加具有相同主键的相同数据模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53532322/

相关文章:

ios - 展开 2 个 View Controller 的转场

iphone - 无需连接即可为 iPhone 构建

android - Android 上的 PWA 是否/可以在隔离的容器或沙箱中运行?

ios - iOS 中使用实时摄像头的 Firebase MLKit 文本识别

swift - 从目录中读取所有文件?

image - 为什么建议将图像存储在磁盘而不是 Realm 中

ios - 具有后台进程的 Realm 实例丢失数据

iOS:在扩展中从 NSNotificationCenter 返回值(swift)

swift - UIWebview 崩溃,错误为 :EXC_BREAKPOINT (CODE=EXC_I386_BPT, SUBCODE = 0X0)

java - Realm :记录顺序已更改