Search code examples
resetnsviewdestroyspawn

Objective-C Reset NSView to Initial state from xib?


I have an NSView with buttons and states that get altered during the course of the program. But is there a way to destroy that view and "respawn" the original one that was in the xib? I can hide and show NSView but what about destroying and recreating a specific view or restoring it to its initial state? Where every component on that view is "reset"? Is it possible to do this?


Solution

  • The way to do what you're asking is to have a separate XIB for the view. Its owner would be your view controller class (subclass of NSViewController). You would allocate an instance of that class and initialize it with the NIB name. When you first request its view property, that will load the NIB with a fresh instance of the view hierarchy. You would then replace the old view with the new view in the superview's subviews and, if you're using auto layout, set the constraints appropriately.

    An easy way to add the view controller class and the view XIB in one step is to do File > New > File > Cocoa class. Set the "Subclass of" combo box to NSViewController. Enter the class name. Check "Also create XIB file for user interface". Click Create and where you want the files saved.

    However, all of that said, the view should not hold state, it should reflect state. The model should hold state and the controller layer should configure the view to reflect the model, including updating it as the model is changed. So, if you've done things right, you should generally just reset your model state and that should reset your view.