I think this is a simple problem, so you might go straight to the question.
I have a global variable, switchStatusIndex, (does not belong to any class.):
import Foundation
//Default
var userIndex:[Int] = [0,1,2]
var userIndexForItem:[Int] = [Int]()
//Index to hold the switch status for all datatypes
var switchStatusIndex:[String] = [
NSUserDefaults.standardUserDefaults().boolForKey("switchA").description,
NSUserDefaults.standardUserDefaults().boolForKey("switchB").description,
NSUserDefaults.standardUserDefaults().boolForKey("switchC").description]
In ViewControllerOne I have a function:
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
setupUserIndexForItem ()
}
func setupUserIndexForItem () {
userIndexForItem = [Int]() //clears userIndexForItem
for i in 0...userIndex.count-1{
if switchStatusIndex[i] == "true"{
userIndexForItem.append(userIndex[i])
}
}
}
Finally I have a ViewControllerTwo with UISwitches ex
@IBOutlet var switchA: UISwitch!
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override func layoutSubviews() {
restoreSwitchesStates()
}
@IBAction func setStateSwitchA(sender: UISwitch) {
var userdefault: NSUserDefaults = NSUserDefaults.standardUserDefaults()
if switchA.on == true {
userdefault.setBool(switchA!.on, forKey: "switchA")
}else if switchA.on == false {
userdefault.setBool(switchA!.on, forKey: "switchA")
}
userdefault.synchronize()
}
func restoreSwitchesStates() {
switchA!.on = NSUserDefaults.standardUserDefaults().boolForKey("switchA")
}
When I flip the switch to .on, it updates NSUserdefault to "true".
However, when I go back to ViewControllerOne, setupUserIndexForItem does not reflect this change. It is as switchStatusIndex does not update.
Question: How can I force a global variable to "update" ?