squarehippo10
squarehippo10

Reputation: 1945

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.

Upvotes: 0

Views: 1198

Answers (2)

RajeshKumar R
RajeshKumar R

Reputation: 15778

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

Upvotes: 1

rmaddy
rmaddy

Reputation: 318934

Put the titles in some sort of data model. You don't want to store the titles in Core Data. That makes localizing your app really difficult. Use your data model to convert the indexes into strings for display on the segmented controls and on other views.

This way your data model can load a set of strings for whatever languages your app supports (now or in the future) and the indexes can return the proper strings in the proper language. And the data model can be used by any number of views in your app.

Upvotes: 1

Related Questions