Reputation: 45
I am trying to debug the below code.
1) CellClass has IBAction to change Bool value, the value declared as value: Bool
@IBAction func dashBrnPressed(_ sender: AnyObject) {
value == true ? (value = false) : (value = true)
NotificationCenter.default.post(name: .reload, object: nil)
// reloads the TableView
}
2) I use UITableView controller with dequeueReusableCell and fetching CoreData. There is these lines only responcible for cell. "switchAction" is a value from CoreData
if cell.value == true{
switchAction.isOn = true
}else{
switchAction.isOn = false
}
DataBaseController.saveContext()
cell.value = switchAction.isOn
return cell
3) it seems to be working unless I restart the app. No crashes but it returns FALSE for value by default. I need store the value back to CoreData depending on what statement the button is.
The code is simplified of course.
Upvotes: 2
Views: 109
Reputation: 45
The reason is still unknowm but this code works
1) cell.value
now is optional and equals nil
while restarting the app
2) This code in cellForRow now firstly assigns optional value and only if the value exist stores the new value 3) function willDisplay doesnt return UITableViewCell and not required
switch cell.value {
case nil:
if switchAction.dashboard == true{
cell.dashBtn.tintColor = .white
cell.value = true
} else {
cell.dashBtn.tintColor = myColors.opaceGrayColor
cell.value = false
}
case true?:
switchAction.dashboard = true
cell.dashBtn.tintColor = .white
DataBaseController.saveContext()
case false?:
switchAction.dashboard = false
cell.dashBtn.tintColor = myColors.opaceGrayColor
DataBaseController.saveContext()
}
I am happy and thank you for help! :)
Upvotes: 0
Reputation: 6810
I think I see the problem. In the block of code under part 2, here's what you're doing:
switchAction.isOn
to the value of cell.value
switchAction.isOn
to CoreDatacell.value
to the value of switchAction.isOn
When you restart your app, cell.value
defaults to false, and then you overwrite that false onto switchAction.isOn
and save it back to CoreData. So even though switchAction.isOn
might be loading with the correct value, you're overwriting it before you ever see it.
What you need is an assignment that goes the other way:
cell.value = switchAction.isOn
Since cell
is a reusable table view cell, you can put that line in your tableView(UITableView, willDisplay: UITableViewCell, forRowAt: IndexPath)
delegate function, which is called right before the cell is displayed.
Upvotes: 1