0

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.

Jonnce
  • 29
  • 1
  • 6
  • 1
    Check out UserDefaults. https://stackoverflow.com/q/31203241/3151675 – Tamás Sengel Apr 12 '18 at 14:49
  • check this one more clear according your question. https://stackoverflow.com/questions/43429699/userdefault-to-save-button-state – MRizwan33 Apr 12 '18 at 15:01
  • I received error message: "Value of type 'NSButton' has no member 'isSelected'" when I tried to use SelfKey.isSelected. Should I use another member in NSButton? – Jonnce Apr 12 '18 at 15:50
  • Possible duplicate of [UserDefault To Save Button State](https://stackoverflow.com/questions/43429699/userdefault-to-save-button-state) – Daij-Djan Apr 12 '18 at 15:52
  • isSelected==true is state==NSOnState – Daij-Djan Apr 12 '18 at 15:53
  • isSelected==false is state==NSOffState – Daij-Djan Apr 12 '18 at 15:53
  • When I tried to set default value SelfKey.state = UserDefaults.standard.bool(forKey: "State") after I set: UserDefaults.standard.set(SelfKey.state, forKey:"State"), I received error: "Cannot assign value of type 'Bool' to type 'NSControl.StateValue". What should I use other than UserDefaults.standard.bool? – Jonnce Apr 12 '18 at 18:31

1 Answers1

2

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")
}
Code Different
  • 90,614
  • 16
  • 144
  • 163