r/macprogramming • u/rudedogg • Nov 11 '18
Anyone using state restoration for views/view controllers?
I'm having the same issue as this person (however my App isn't document based, no IB for the code in question): https://stackoverflow.com/questions/42010026/nsviewcontrollers-and-nsviews-are-not-getting-restoration-api-calls
Has anyone been able to get state restoration working? I've just been using UserDefaults, but I feel like the restoration API would be cleaner.
Here's what I have in my NSViewController:
override func encodeRestorableState(with coder: NSCoder) {
super.encodeRestorableState(with: coder)
coder.encode(imageDisplayModeSegmentedControl.selectedSegment, forKey: "selectedImageDisplayModeSegment")
}
override func restoreState(with coder: NSCoder) {
super.restoreState(with: coder)
let selectedImageDisplayIndex = coder.decodeInteger(forKey: "selectedImageDisplayModeSegment")
imageDisplayModeSegmentedControl.selectedSegment = selectedImageDisplayIndex
}I set a breakpoint and these are never called. Calling invalidateRestorableState() doesn't cause them to be called either.
Any help/advice would be appreciated!
Edit: I think the API serves a different purpose than I was hoping. I just wanted to save some options the user had selected on the last use, but the API seems to be more about restoring state from a crash, or the "reopen windows" option when you restart. I don't really want to worry about that yet though. So I'll keep using UserDefaults for now.
2
u/BaumGardine Nov 11 '18
Im just guessing but maybe your views arent in the responder chain. Try Putting smth like a textfield in it, so you definitly have a First responder
1
u/mantrap2 Nov 11 '18
You should be relying on your existing MVC code to update ANY view/ui elements. State restoration should only be upon your model data.
2
u/quellish Nov 15 '18
Try adding @objc annotations to the methods. The objc inference in swift 4 tends to screw up system callbacks.