Search code examples
swiftxcodensbutton

NSButton value as default in swift


I am a newbie in swift using Xcode trying to write a small checklist app. After I check/uncheck the checkbox and exit the app, the state just disappears next time when I reopen it next time. I am wondering how can I save the current state of NSButton as default so that next time when I open the app, it will show up the same state when I closed it. I tried below practice:

Set default value:

@IBAction func Check1(_ sender: NSButton) {
        UserDefaults.standard.set(Check1.state, forKey:"Check1status")
    }

Read default value:

override var representedObject: Any? {
    didSet {
        Check1.state = UserDefaults.standard.bool(forKey:"Check1status")
    }
}

However I received error message:"Cannot assign value of type 'Bool' to type 'NSControl.StateValue'"

How can I fix this error? Thanks.


Solution

  • Because state is not a boolean value. In Objective-C, it's an integer. In Swift, it's a struct whose rawValue is an integer. Also, don't set the state in representedObject.didSet. Do it in viewDidLoad:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        // When your app launches for the very first time on the user computer, set it to On
        UserDefaults.standard.register(defaults: [
            "Check1Status": NSControl.StateValue.on.rawValue
        ])
    
        let state = NSControl.StateValue(UserDefaults.standard.integer(forKey:"Check1status"))
        check1.state = state
    }
    
    @IBAction func check1(_ sender: NSButton) {
        // Swift performs do some background magic if you type check1.state
        // Adding rawValue make it clear that you are writing an integer to the UserDefaults
        UserDefaults.standard.set(check1.state.rawValue, forKey:"Check1status")
    }