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> {

    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];

    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>
    - (void)validate;
    @protocol VRControlValidations
    - (BOOL)validateControl:(id <VRValidatedControl>)item;
  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

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive:

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020