Search code examples
objective-ccocoaobserver-pattern

Is there a standard pattern for managing object state in different Cocoa views and menus?


In a Cocoa application is there a standard pattern for keeping UI and other element states in sync? For example I have the main Menu managed by one class and a toolbar managed by another. Some of the menu items must reflect current selections in the toolbar and vice versa. I was going to handle this by having the selector triggered by the menu items and toolbar items fire off a Notification. The controlling classes would subscribe to these an update the UI to match the selection. Is this a good way to do this or am I missing some other natural way to do this in Cocoa?


Solution

  • For the specific case of whether an item should be enabled or disabled, that should be left to the target (or the implicit target if the target is the first responder). It should use User Interface Validation for that.

    Bindings is another good technique. The state which governs the UI should either be in the model or the controller, and the UI should bind to it. (If the UI is to bind to the model, it should be through the controller.) That way, you only have to make sure the state is up-to-date and consistent and everything else happens automatically.

    But then the technique you describe is a good third option. The model should provide notifications (through NSNotifications or a delegate) to the controller layer when it has changed. The controller layer watches those and has intimate knowledge about what effect state changes should have on the UI and explicitly configures the UI to conform.