【问题标题】:Best way to update nested property in BehaviourRelay在 BehaviourRelay 中更新嵌套属性的最佳方法
【发布时间】:2021-05-17 17:28:35
【问题描述】:

我有以下型号

final class Vehicle {
var cars:[SportsCar] = []
}

final class SportsCar {
var isCheap:Bool = false
}

假设 Vehicle 和 SportsCar 都是 Equatable(为简单起见,我省略了 Equatable 一致性)。

目标:更新嵌入在 Vehicles BehaviorRelay 继电器内的汽车数组中的汽车之一的 isCheap 属性。

尝试:

final class ViewModel {
    let vehicles:BehaviorRelay<[Vehicle]> = BehaviorRelay(value: [])
    // Attempt 1: Access vehicles direct without making a copy.
    
    // Toggling `isCheap` property when user tap a button on a collectionView cell.
    func updateCarProperty(checkedVehicle:Vehicle,checkedIndexPath:IndexPath){
        for car in vehicles.value[checkedIndexPath.section].cars {
            let checkedCar = checkedVehicle.cars[checkedIndexPath.item]
            if car == checkedCar {
                if car.isCheap {
                    vehicles.value[checkedIndexPath.section].cars[checkedIndexPath.item].isCheap = false
                }else {
                    vehicles.value[checkedIndexPath.section].districts[checkedIndexPath.item].isCheap = true
                }
                break
            }
        }
    }
    
}


// Attempt 2: Make a copy of vehicles then use it to change the property then on completion update the whole vehicles array by calling
//vehicles.accept(vehiclesCopy)
// As described on this answer: https://stackoverflow.com/a/58295908/7551807
// This approach didn't work too.

期望:当函数调用完成时,Car isCheap 属性会改变。

结果:该属性没有按预期更改????。无论如何,它都保持为默认值(false)!!

问题:还有其他更好的方法来处理这个问题吗?

【问题讨论】:

    标签: rx-swift rx-cocoa


    【解决方案1】:

    您必须创建对象的全新副本并将其发送到中继。您不能发出“子集”或继电器的类型,因为它发出 [Vehicle] 类型的值,因此您必须始终向其发送新的车辆数组。

    您必须创建车辆数组的副本,改变所需的项目,然后使用 .accept(updatedVehicles) 将整个数组发回。

    【讨论】:

    • 谢谢@Shai,似乎是要走的路。我想我现在在修复模型时遇到了另一个问题!
    猜你喜欢
    • 2014-04-17
    • 2018-12-08
    • 2021-03-25
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    • 2020-11-26
    • 1970-01-01
    相关资源
    最近更新 更多