ios - Realm, Swift, 多对多关系

标签 ios swift realm

在我的 API 上,我在 Stands 和 Products 之间建立了关系。哪些展位有产品,但也可以在不同的展位找到产品。我正在尝试使用 Realm 在我的 iOS 应用程序上复制这种关系,但我似乎无法让它工作。

建立这种关系的目的是能够搜索销售特定产品的展台。

我的模型:

class Stand: Object {
    dynamic var id : Int = 0
    dynamic var name : String = ""
    dynamic var latitude : Double = 0.0
    dynamic var longitude : Double = 0.0
    let products = List<Product>()

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

class Product: Object {
    dynamic var id : Int = 0
    dynamic var name : String = ""
    let stands = List<Stand>()

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

当我对 Stands 发出 API 请求时,我也会用它检索相关的产品。当我将这些附加到 Stands 时,它适用于我的 Stands 模型,因为产品通常只是添加到 List() 中。

但所有产品都是单独创建的,没有附加任何支架。

有没有办法在创建产品时直接将这些展台分配给产品?就像事情反过来发生一样?

我目前的解决方案是..

func retrieveAndCacheStands(clearDatabase clearDatabase: Bool?) {
    backend.retrievePath(endpoint.StandsIndex, completion: { (response) -> () in
        let listOfProducts : List<(Product)> = List<(Product)>()

        func addProducts(stand: Stand, products: List<(Product)>?) {
            for product in products! {
                print(product.name)
                let newProduct = Product()
                newProduct.id = product.id
                newProduct.name = product.name
                newProduct.stands.append(stand)

                try! self.realm.write({ () -> Void in
                    self.realm.create(Product.self, value: newProduct, update: true)
                })
            }

            listOfProducts.removeAll()
        }

        for (_, value) in response {
            let stand = Stand()
            stand.id = value["id"].intValue
            stand.name = value["name"].string!
            stand.latitude = value["latitude"].double!
            stand.longitude = value["longitude"].double!
            for (_, products) in value["products"] {
                let product = Product()
                product.id = products["id"].intValue
                product.name = products["name"].string!
                stand.products.append(product)
                listOfProducts.append(product)
            }

            try! self.realm.write({ () -> Void in
                self.realm.create(Stand.self, value: stand, update: true)
            })

            addProducts(stand, products: listOfProducts)
        }

        print(Realm.Configuration.defaultConfiguration.path!)

        }) { (error) -> () in
            print(error)
    }
}

这会存储 Stands 并向其添加 Products。它还会创建所有产品并为每 10 个产品添加 1 个展位(?)。

我似乎无法弄清楚如何进行这项工作。有没有人知道如何解决这个问题?或者更好的解决方案?

最佳答案

您应该使用 Realm 的反向关系机制,而不是手动维护反向关系所需的双重簿记,它为您提供所有指向使用给定属性的另一个对象的对象:

class Product: Object {
    dynamic var id: Int = 0
    dynamic var name: String = ""
    // Realm doesn't persist this property because it is of type `LinkingObjects`
    // Define "stands" as the inverse relationship to Stand.products
    let stands = LinkingObjects(fromType: Stand.self, property: "products")

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

请参阅 Inverse Relationships 上的 Realm 文档获取更多信息。

关于ios - Realm, Swift, 多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34276659/

相关文章:

ios - SpriteKit 中的场景

ios - Swift : How $0 works in Array. forEach?

ios - Realm :更新属性缓慢

arrays - Realm swift : manipulate arrays with realm object

ios - Swift Realm 响应结果不同

ios - 如何在字符串操作时获取ios中某些特殊字符之间的数据

ios - 如果在 View Controller 1 上选择了我的 "button",则图像应该显示并保留在 View Controller 2 上

iphone - UILabel 不会自动缩小文本以适应标签大小

ios - 如何将 .movpkg 转换成 mp4

ios - 在 Swift 中 stub HTTP 请求