Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Apple > Operating Systems

  • Print
  • + Share This
This chapter is from the book

Step 4: Validate the Add Tag Push Button

Good user interface design requires, among other things, that you take pains to avoid confusing the user. One potential source of confusion is user interface elements that look as though they're available but don't do anything. For this reason, many controls and other user interface elements can be enabled or disabled, with distinctive visual differences that users have come to understand. These include toolbar items, menu items, and all kinds of buttons. You should make sure that your application's eligible UI elements are disabled whenever the state of the application is such that they aren't functional.

In this step, you disable the Add Tag button when the insertion point in the active text view is positioned in an area that has no entry marker preceding it. Either the text view is empty, or the insertion point is located in an untitled preface. The application specification forbids tag titles in these circumstances, so the Add Tag button should be disabled. In all other circumstances, it should be enabled.

You enable and disable a button by sending it the -setEnabled: message with a parameter value of YES to enable it or NO to disable it. The straightforward way of doing this is to declare an outlet for the control, write accessor methods to get the outlet and perhaps set it, and connect the outlet in Interface Builder. Then you can send the outlet a setEnabled: message at the right time.

It is common practice to call the -setEnabled: method multiple times in a custom method that validates every user interface item in a window. The custom method is typically named something like -updateWindow. An application might call the -updateWindow method from several other methods, perhaps once from -awakeFromNib or -windowDidLoad to validate controls when the window first opens, and then again from any method that is called when an event occurs that requires the window's controls to be validated again.

Sending a message directly to a connected outlet is fast, but this technique requires you to do a significant amount of work every time you add a new control to the application. In a complex application, you may end up declaring, implementing, and connecting dozens or even hundreds of outlets.

Cocoa offers a more generalized way to perform user interface validation, the NSUserInterfaceValidations protocol, which you use in this step. It saves you the trouble of having to declare and connect all those outlets. It also has the advantage of integrating automatically with menu item validation, saving you even more effort. In this context, validation refers to the control's enabled or disabled state. The term is used in other contexts to mean something different, such as determining whether the content of a text field or the value of a date picker is valid and should be shown or hidden.

Before going any further, read the "Protocols" sidebar to understand what a protocol is.

The basic concept underlying the NSUserInterfaceValidations protocol is that a single method in a controller class holds all the code that is required to decide whether to enable or disable all of the UI elements within the controller's jurisdiction. That method is the sole method declared in the NSUserInterfaceValidations protocol, -validateUserInterfaceItem:, which you will implement. It is important to name it -validateUserInterfaceItem: and to declare that your controller conforms to the protocol so that other parts of Cocoa are aware of it.

The parameter to the -validateUserInterfaceItem: protocol method is an eligible user interface item, such as a toolbar item, a menu item, or a validated control. In the body of the method, you ascertain the identity of the specific item by its action method (or, rarely, by its tag). The item must conform to the related NSValidatedUserInterfaceItem protocol or to a custom validation protocol that you declare. Technically, conformity to the NSValidatedUserInterfaceItem protocol guarantees that the item implements the -action and -tag methods. In practice, conformity also means that the item implements a -setEnabled: method and is meant to be validated using the techniques described here. You then specify the conditions under which the item should be enabled or disabled. You arrange for the method to return YES if the current state of the application is such that the item should be enabled, or NO if it should be disabled. You don't have to declare or connect outlets to the items because each item in succession is passed into the protocol method.

For the Add Tag button, for example, your implementation of the -validateUserInterfaceItem: method first ascertains whether the item's action is the addTag: action. If it is, the method tests whether the insertion point in the diary window's active text view is within a diary entry. If so, the method returns YES; if not, it returns NO. If the item's action is not the addTag: action, the method returns YES so that all the other items in the window are enabled. You have to do this because the protocol method may be called on other items in the window that you don't intend to validate.

The trick is to know when and how to call the -validateUserInterfaceItem: protocol method. Cocoa automatically validates two kinds of user interface items, menu items and toolbar items, if you implement -validateUserInterfaceItem: or the more specialized -validateMenuItem: and -validateToolbarItem: methods. Cocoa handles controls such as buttons differently. You still have to implement -validateUserInterfaceItem: or a more specialized validation method, but Cocoa does not call them automatically. You have to call them yourself whenever changes to the window require validation of controls.

To understand how validation works, consider first -validateMenuItem: and -validateToolbarItem:. Cocoa calls these methods automatically if you implement them, much like the automatic invocation of delegate methods that you have implemented. Menu items are validated when an NSMenu object's -update method is called, and toolbar items are validated when an NSToolbar object's -validateVisibleItems method or an NSToolbarItem object's -validate method is called. In the case of menu items, validation occurs whenever the user opens a menu and thus triggers its -update method. In the case of toolbar items, validation occurs when an NSWindow object's -update method calls the toolbar's -validateVisibleItems method, which happens in every iteration of the run loop. You can override these methods to make them more efficient if your validation code takes too much time. You can call NSMenu's -setAutoenablesItems and NSToolbarItem's -setAutovalidates: method to turn automatic validation of menu items and toolbar items on or off. The final point to understand is that menu item and toolbar item validation falls back on -validateUserInterfaceItem: if you implement it and don't implement -validateMenuItem: or -validateToolbarItem:. This is important because it allows you to put validation code in a single method, -validateUserInterfaceItem:, if your application has controls and menu items that respond to the same action message, as most applications do. You will do this in Recipe 5 by adding an Add Tag menu item and others duplicating the actions of some of the controls, which will be validated by the same -validateUserInterfaceItem: protocol method you implement here.

To use the -validateUserInterfaceItem: protocol method with controls, the end result is the same, but the way you set it up is a little different. You have to supply some of the support for validated controls, whereas Cocoa provides this support for you in the case of menu items and toolbar items. Your application not only must implement the -validateUserInterfaceItem: protocol method, but also must call the protocol method explicitly for controls. Alternatively, your application can implement and call a more specialized validation method analogous to -validateMenuItem: and -validateToolbarItem:, which you might name something like -validateControl:. The documented way to do this follows the same pattern that is built into Cocoa for menu items and toolbar items. You declare two custom protocols; you subclass the controls that are to be validated, so that they conform to one of the protocols and implement its required validation method; and finally, you call the controls' validation methods from your controller whenever the user changes the state of the window. You implement the documented technique in Vermont Recipes. See the "Implementing a Validated Item" section of User Interface Validation for details.

Normally, you validate user interface items every time the control's window is updated. You could do this, for example, in your implementation of NSWindow's -windowDidUpdate: delegate method, which the system calls automatically every time the window updates—that is, once in every iteration of the run loop. If the application's logic is clear or speed is an issue, you can be more discriminating and validate controls only in response to specific relevant events, but you shouldn't go that route until profiling of your finished application demonstrates a real performance issue.

Here, you start by declaring two protocols, VRValidatedControl and VRControlValidations. Protocol names must be unique. The Objective-C Programming Language indicates that they do not have global visibility and live in their own namespace, unlike classes. Nevertheless, you should name them with a prefix consisting of two or three uppercase letters to minimize the risk of namespace collision with frameworks you import from Apple or a third party. Here, you use VR, for Vermont Recipes. The VRValidatedControl protocol declares a single method, -validate. You label it @required, because every validated control must implement this method. The VRControlValidations protocol declares the optional method -validateControl:. Then you implement a subclass of NSButton named ValidatedDiaryButton, and you declare that it conforms to the VRValidatedControl protocol. Conformity means that the button implements the -validate method. You implement -validate to call the controller's -validateControl: method, if it implements one, and if not, to fall back on the controller's -validateUserInterfaceItem: protocol method. Finally, in the window controller, you implement -validateUserInterfaceItem: to perform the tests needed to decide whether the control should be enabled or disabled, and you call it on every validated control when the window updates, once in every iteration of the run loop.

The controller could implement -validateControl: instead of -validateUserInterfaceItem:, but for the Chef's Diary window you want to have a number of menu items that perform the same actions as the validated buttons.

  1. Start by implementing the protocol method, -validateUserInterfaceItem:. Enter it in the DiaryWindowController.m source file, following the existing -windowDidLoad method. You don't have to declare it in the header file because it is declared in the NSUserInterfaceValidations protocol.

    - (BOOL)validateUserInterfaceItem:
           (id <NSValidatedUserInterfaceItem>)item {
         SEL action = [item action];
         if (action == @selector(addTag:)) {
              return ([[self document] currentEntryTitleRangeForIndex:
                     [self insertionPointIndex]].location != NSNotFound);
         }
         return YES;
    }

    You will arrange shortly to call this method in a loop, once for every view in the window that conforms to the VRValidatedControl protocol. Only some of the controls will conform to it. Every time the method is called, a reference to a particular validated user interface item is passed to it in the item parameter. The type of the parameter is id to allow any kind of control to be validated. In Step 6, you will in fact validate the diary window's date picker, which is not a button.

    The item must conform to the NSValidatedUserInterfaceItem protocol because of the reference to the protocol in angle brackets as part of the type declaration. Every item that conforms to the VRValidatedControl protocol meets this condition, because you will shortly declare the protocol to inherit from the NSValidatedUserInterfaceItem protocol.

    You test the current item value to determine whether its action is the addTag: action. If it is, then this must be the Add Tag button (or an Add Tag menu item that sends the same action), so you return a Boolean value of YES or NO depending on whether the -currentEntryTitleRangeForIndex: method returns a range whose location member is NSNotFound. If this item is not the Add Tag button, the method falls through the if clause and returns YES in all other cases, because for now, at least, all other buttons in the window should always be enabled. You will shortly add additional if clauses to test for other validated buttons. A typical -validateUserInterfaceItem: method might have many if clauses.

    This is not the first time you have encountered an Objective-C selector, but it wasn't previously singled out as a distinct feature of the language. You have seen selectors every time you connected a user interface element in Interface Builder and chose an action. A selector is a language element of type SEL. Look up the -action method in the NSControl Class Reference, and you see that it returns a value of type SEL. To test whether this action is a particular selector, you use the @selector compiler directive, passing in the selector, or action, you're interested in. As you see here, a selector is simply the method's signature, including all colons marking parameters and the parameter labels, which uniquely identifies this action. Note that the selector is not a string object. Should you ever want to display a selector, perhaps in an NSLog() function call for debugging purposes, use the Cocoa NSStringFromSelector() function.

  2. Because the DiaryWindowController class now implements the -validateUserInterfaceItem: protocol method, you should change its header file to advertise this fact. In DiaryWindowController.h, change the @interface directive to this:

    @interface DiaryWindowController :
           NSWindowController <NSUserInterfaceValidations> {
    }

    As you see, you declare conformity to a formal protocol by placing its name in angle brackets at the end of the @interface directive. This is known as the protocol list. To declare conformity with multiple protocols, separate them with commas in the protocol list.

  3. Next, implement the method that calls the -validateUserInterfaceItem: protocol method. In Vermont Recipes, this is a custom -updateWindow method. Place it after the existing -windowDidLoad method.

    In the DiaryWindowController.h header file, declare it like this:

    - (void)updateWindow;

    In the DiaryWindowController.m source file, implement it like this:

    - (void)updateWindow {
        for (id thisView in [[[self window] contentView] subviews]) {
             if ([thisView conformsToProtocol: 
                   @protocol(VRValidatedControl)]) {
                  [thisView validate];
             }
        }
    }

    The method loops through all the subviews in the diary window's content view using the new fast enumeration syntax in Objective-C 2.0. In each iteration of the loop, it tests whether the current view conforms to the VRValidatedControl protocol. A protocol is specified for purposes of the -conformsToProtocol: method using the @protocol directive, which is similar to the @selector directive. Most of the views in the window do not conform, including the Add Entry button. They are therefore skipped.

    When the Set Tag button is checked in the loop, it meets the test. It conforms to the protocol because you are about to make it so. The method therefore calls this control's -validate protocol method, which does the work of enabling or disabling the control.

  4. Next, arrange to call the new -updateWindow method at the appropriate times—namely, whenever the window updates. To do this, implement NSWindow's -windowDidUpdate: delegate method immediately before the -updateWindow method, like this:

    - (void)windowDidUpdate:(NSNotification *)notification {
         [self updateWindow];
    }

    It may seem wasteful to implement a separate -updateWindow method when its body could have been placed directly in the -windowDidUpdate: delegate method. Over time, however, you may find that you sometimes need to call an -updateWindow method from other methods as well as from the delegate method, so it can be convenient to make it a separate method now.

  5. None of this works unless the Set Tag button actually does conform to the VRValidatedControl protocol. Objective-C tests conformity to formal protocols by checking whether a class's @interface directive includes the protocol in angle brackets in the protocol list. Cocoa does not check to see whether the class actually responds to the methods required by the protocol; it is the programmer's responsibility to implement them if the class declares that it conforms.

    To make validation work here, you must therefore declare and implement a subclass of NSButton and declare that the subclass conforms to the VRValidatedControl protocol. The new subclass—call it ValidatedDiaryButton—has to implement only one method, namely, the -validate protocol method. It inherits the other methods it needs, -action and -setEnabled:, from NSButton.

    The subclass is relevant only to the diary window, so it is appropriate to declare and implement it in the DiaryWindowController files. At the end of the DiaryWindowController.h header file, after the @end directive, declare it like this:

    @interface ValidatedDiaryButton : NSButton <VRValidatedControl> {
    }
    @end

    It doesn't declare the -validate method because it declares conformity to the VRValidatedControl protocol, which does declare it, thus guaranteeing that it implements that method.

    At the end of the DiaryWindowController.m implementation file, after the @end directive, implement it like this:

    @implementation ValidatedDiaryButton
    - (void)validate {
         id validator =
                [NSApp targetForAction:[self action]
                to:[self target] from:self];
         if ((validator == nil)
                || ![validator respondsToSelector:[self action]]) {
              [self setEnabled:NO];
         } else if ([validator respondsToSelector:
                @selector(validateControl:)]) {
              [self setEnabled:[validator validateControl:self]];
         } else if ([validator respondsToSelector:
                @selector(validateUserInterfaceItem:)]) {
              [self setEnabled:[validator validateUserInterfaceItem:self]];
         } else {
              [self setEnabled:YES];
         }
    }
    @end

    If you decide later to add any buttons to the window that require validation and are subclasses of NSButton, such as NSPopUpButton, you will have to declare them as validated subclasses as well. You can also add other controls in the same way. In Steps 6 and 7, for example, you will validate the diary window's date picker and search field in this manner, although they are not subclasses of NSButton.

  6. There is one more thing to do before you declare the protocols that lie behind this validation technique. At this point, the Set Tag button still thinks its class is NSButton, which does not conform to the protocol. You have to change its class to ValidatedDiaryButton.

    First, build the application. Then, in Interface Builder, select the Set Tag button in the diary window. In the Button Information inspector, choose ValidatedDiaryButton from the Class pop-up menu. Save the nib file, and build the application again.

  7. Finally, you're ready to declare the protocols. This may come as an anticlimax after all that, because there is nothing to it.

    Near the end of the DiaryWindowController.h header file, just above the new -ValidatedDiaryButton declaration, insert these two protocol declarations:

    @protocol VRValidatedControl <NSValidatedUserInterfaceItem>
    @required
    - (void)validate;
    @end
         
    @protocol VRControlValidations
    @optional
    - (BOOL)validateControl:(id <VRValidatedControl>)item;
    @end
  8. Run the application and test the Add Tag button. When you first open a new diary window, the button is disabled, as it should be, because there is no entry title before the insertion point. Now type a few characters, press the Return key, and click Add Entry. The Add Tag button immediately becomes enabled because the insertion point is now positioned after the new diary entry's title marker and is thus in the current entry. Click Add Tag, and a new tag list appears. Move the insertion point before the entry's title marker, using the mouse button or the arrow keys on the keyboard, and the Add Tag button immediately becomes disabled.

  • + Share This
  • 🔖 Save To Your Account