如何正确地快速更新领域数据库上的数组列表数据?

时间:2018-12-18 04:30:54

标签: ios swift realm

我有这样的产品领域对象:

class Product : Object {

    @objc dynamic var productID : String = ""
    @objc dynamic var name : String = ""
    @objc dynamic var unitPrice: Double = 0.0
    @objc dynamic var quantity = 0
    @objc dynamic var descriptionProduct : String = ""
    @objc dynamic var hasBeenAddedToWishList : Bool = false
    @objc dynamic var hasBeenAddedToCart : Bool = false
    @objc dynamic var isNewProduct : Bool = false
    var imagePaths = List<String>()

    override static func primaryKey() -> String? {
        return "productID"
    }

    func toDictionary() -> [String:Any] {
        return [
            "productID" : productID,
            "name" : name,
            "unitPrice": unitPrice,
            "quantity": quantity,
            "descriptionProduct": descriptionProduct,
            "hasBeenAddedToWishList": hasBeenAddedToWishList,
            "hasBeenAddedToCart": hasBeenAddedToCart,
            "isNewProduct": isNewProduct,
            "imagePaths": imagePaths
        ]
    }

}

我想使用此功能更新产品数据:

 static func updateProductDataInRealmDatabase(oldProductData: Product, newProductData: Product) {

        guard let matchingProduct = RealmService.shared.realm.objects(Product.self).filter("productID == %@", oldProductData.productID).first else {return}

        var newDataProductDictionary = newProductData.toDictionary() // the definition of toDictionary is in above code
        newDataProductDictionary["productID"] = nil   // to avoid updating the primary key

        RealmService.shared.update(object: matchingProduct, for: newDataProductDictionary)

    }

这是用于更新数据的领域服务的定义:

class RealmService {

    private init() {}
    static let shared = RealmService()

    var realm = try! Realm()

    func update<T: Object>(object: T, for dictionary: [String: Any]) {

        do {

            try realm.write {

                for (key,value) in dictionary {
                    object.setValue(value, forKey: key)
                }

            }

        } catch {
            post(error)
        }

    }


}

实际上,我可以将某些数据更新为新数据,例如productNameproductPrice etc,但是我无法更新imagePaths属性,即{{1} }

在更新数据后,数组将始终为零,如下图所示,imagePaths数组为零:

enter image description here

那么如何正确更新产品数据?特别是更新我的领域对象中的列表数据。这里出了什么问题?我使用下面的代码更新领域数据库:

List<String>

1 个答案:

答案 0 :(得分:1)

由于Product类已经具有主键,因此无需使用productID搜索现有的领域对象。 Realm将使用下面提到的此查询添加新对象或更新旧对象。

您可以像这样查询。

let realm = try! Realm()

try! realm.write {
realm.add(anyProductObject,update: true)
}
// You can customize this using generics and also use try catch to handle the errors in case you pass the non realm defined class object