Search code examples
iosswiftcore-datauisegmentedcontrol

how to save the index and title of a segmented control in core data


I have a dozen segmented controls. I save the selected index for each one in Core Data. My entity is called Worksheet and each index is saved as an Int. That part works great.

The problem is that I want to display the selected titles in a different view. But I obviously can't just grab the index from Core Data. My new view has no idea what those numbers stand for. I know that CoreData can't save tuples, though, that would make things much easier.

I have tried creating a transformable attribute, and a custom managed object, but the first won't work for tuples, and I can't seem to wrap my head around the second. The title and the index don't seem like they should be separated.


Solution

  • Create a enum for every SegmentedControls with CaseIterable

    enum Planet: String, CustomStringConvertible, CaseIterable {
        case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
        var description: String {
            return self.rawValue.capitalized
        }
    }
    

    And use the Planet.allCases array to create the segments for the segmented control

    let segmentedControl = UISegmentedControl(items: Planet.allCases)
    

    or

    Planet.allCases.enumerated().forEach {
        segmentedControl.insertSegment(withTitle: $1, at: $0, animated: true)
    }
    

    When selection changed in the segment control save the selected index in core data.

    @objc func indexChanged(_ sender: UISegmentedControl) {
        print(Planet.allCases[sender.selectedSegmentIndex])
        //save sender.selectedSegmentIndex in core data
    }
    

    When you want to display the selected titles in a different view, get selected indexes from core data. And get the corresponding string value from the Enum.allCases array

    let selectedPlanetIndex = 5//Index fetched from core data
    let selectedPlanetTitle = Planet.allCases[selectedPlanetIndex]//saturn