In a Cocoa document-based application, what's the best way to keep the menu item states in the menu bar in sync with the currently visible document?
For example, say you have a document with a ruler view that can be hidden/shown via "Show Rulers" (off state) and "Hide Rulers" (on state) menu items. The user has two documents open at the same time. He/she has hidden the rulers in one document, but not on the other. When the user moves between the documents the menu item should reflect the state for that document, not for the application as a whole.
How does one do this cleanly? I've googled around but it doesn't seem like there's a predefined "out of the box" way to do this. It would be nice if NSDocument had some sort of "didRegainFocus" type method where such logic can be added.
My actual implementation is a bit trickier since it's actually a NSViewController inside my NSDocument that deals with these particular menu items.
@interface MyDocument : NSDocument {
SomeViewController *myCustomizedTextViewController;
}
When MyDocument
is the currently active document, I need methods in myCustomizedTextViewController
to ensure the state of a couple of NSMenuItem
s in the application's main menu. One is genuinely a ruler. The other is a similar temporary setting.
Have the target of the menu items implement the
validateUserInterfaceItem:
method to enable/disable them. See the User Interface Validation reference for more info.