swiftuitableviewkey-value-observing

Swift Checklist - Saving the Switch Data for multiple Rows


So I have a Simple UITableView that will display a UILabel and a UISwitch. I need to be able to get the values of each switch update my object then eventually send the data the API. I has a semi working concept. But this only worked if ALL the cells were visible. Before I only had 5 items to be checked. So I could simply loop through everything and get the data. Now my checklist has grown to over 20 items.

I understand to a degree why the current code doesn't work. It finds nil values. That would be the cells that aren't visible.

My big question is how do i go about capturing the value of all the cells and the value of all the UISwitch values and update my object?

I tried to use the KVO method. This is what I have so far, I have never used this before and a bit lost:

private var observation: NSKeyValueObservation?

observation = switchCell.observe(\.switchOne, options: [.old, .new]) { value, change in
    print("value: \(value.switchOne.isOn)")
    print("change old: \(change.oldValue)")
    print("change new: \(change.newValue)")

}

My issue is I am not sure what I am supposed to use for the key path. Iget the following warning:

Passing reference to non-'@objc dynamic' property 'switchOne' to KVO method 'observe(_:options:changeHandler:)' may lead to unexpected behavior or runtime trap

Then the simulator doesn't boot up. What is the easiest way/best way to do this? Like I said I have 2)+ items on my checklist as I completed each item, I turn the switch on. Then I need to get the value for each item, and update the object with the correct value. Then I send the data to the API to store the info to the database. From what I was reading this seemed to be the right direction.


Solution

  • store predefined status of switches in array of dictionary like:

    let alreadyYouHaveThis = [["id": 1, "title": "name"...., ], [ "id": 1, "title": "name"....., ],["id": 1, "title": "name"...., ]
    
    just add one more key in the same data like status...
    
    let updatedData = [["status": true, "id": 1, "title": "name"...., ], ["status": true, "id": 1, "title": "name"....., ],["status": false, "id": 1, "title": "name"...., ]
    

    now that status will be used in cellforindexpath method as other:

    func cellforindexpath() ..... {
    let status = data[indexPath.item]["status"]
    swithc.tag = indexpath.item
     setswitchstatus on above value
    }
    
    and action for switch : 
    @Objc func switchStatus(_ switch: UISwitch) {
        let status = data[switch.tag]
        status != status
        data[switch.tag]["status"] = status
    ....
    }
    

    or can edit main data source and add these status in that data.

    if you cant perform this let me know.