Coder221
Coder221

Reputation: 1433

Store day values individually in core data

I have 7 buttons for days of a week, which have tags from 1 to 7. I like to store those values in core data when tapped. Since arrays are not allowed in core data, how do I individually store them in core data?

Initially, I was getting tags from the button like these

@IBAction func dayButtonPressed(_ sender: Any) {
        guard let button = sender as? UIButton else { return }

    if(dayTag.contains((sender as AnyObject).tag!)) {
        if let index = dayTag.firstIndex(of: (sender as AnyObject).tag!) {
            dayTag.remove(at: index)
        }
    } else {
        dayTag.append((sender as AnyObject).tag!)
    }
}

and storing them to core data as follows

  object.setValue(dayTag, forKey: "days")

I am not getting any idea of how to create 7 individual variables and store them into core data when the button is tapped. Any, help in the direction would be appreciated.

Upvotes: 0

Views: 69

Answers (1)

vadian
vadian

Reputation: 285069

A reasonable solution is a computed property.

Declare days as

@NSManaged var days: String

and declare a computed property

var weekdays : [Int] {
    get { return days.components(separatedBy: ",").map{Int($0)!) }
    set { days = newValue.map(String.init).joined(separator: "," }
}

Setting weekdays converts the Int array to a comma separated string and updates days (and vice versa).

Upvotes: 1

Related Questions