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 6: Implement and Validate the Date Picker

A Cocoa date picker control serves two useful purposes in the Vermont Recipes application.

First, the date picker acts as a more discriminating goTo control than the four navigation buttons. The navigation buttons are limited to the first, last, previous, and next entries. Even the most experienced chef will quickly generate more diary entries than that. Since each entry is titled with the date when it was created, a date picker is a perfect control to navigate to a specific entry. In this step, you code the date picker to navigate to the first, or oldest, entry that is equal to or more recent than the date entered in the date picker. In other words, the date picker's setting defines the oldest entry that the user wants to select. In the special case where there is no entry more recent than the date picker's setting, it navigates to the most recent entry in the diary.

Second, the date picker acts as a title for the current entry, so the user can see at a glance which entry is currently active even if its title has scrolled off the top of the window. It is updated automatically, as the user navigates through the diary, to display the date of the current entry. It should do this only when the user is not using the date picker itself to navigate. When the date picker is in use, it shows the date being set by the user. It reverts to displaying the current entry's date when the user returns keyboard focus to the text view.

When the date picker is not in use and there is no current entry—that is, when the text view is empty or the insertion point is in an untitled preface—the date picker defaults to displaying the current date.

Implement the date picker's action method first, and then turn to its role as title for the current diary entry.

  1. Cocoa's NSDatePicker class inherits from NSControl, so it responds to NSControl's -action method. Start by implementing a -goToDatedEntry: action method, on the model of the other goTo methods. It will have to call a new range method, which you will write shortly.

    In the DiaryWindowController.h header file, declare the action method after the last of the other goTo action methods:

    - (IBAction)goToDatedEntry:(id)sender;

    In the DiaryWindowController.m source file, define it like this after the last goTo... method:

    - (IBAction)goToDatedEntry:(id)sender {
         NSTextView *keyView = [self keyDiaryView];
         NSRange targetRange =
                [self firstEntryTitleRangeAtOrAfterDate:[sender dateValue]];
         if (targetRange.location != NSNotFound) {
             [keyView scrollRangeToVisible:targetRange];
             [keyView setSelectedRange:targetRange];

    Only two features distinguish this from the other goTo action methods: It calls a different range method, -firstEntryTitleRangeAtOrAfterDate:, which you have yet to write, and it does not return keyboard focus to the text view.

    The latter point is important for usability. The date picker should remain in control until the user explicitly clicks in the text view. This allows the user to continue changing the settings on the date picker without interruption.

  2. Write the -firstEntryTitleRangeAtOrAfterDate: range method. Like the other range methods, it belongs in DiaryDocument.

    In the DiaryDocument.h header file, declare it following -nextEntryTitleRangeForIndex: as follows:

    - (NSRange)firstEntryTitleRangeAtOrAfterDate:(NSDate *)date;

    In the DiaryDocument.m implementation file, declare it in the same relative location, like this:

    - (NSRange)firstEntryTitleRangeAtOrAfterDate:(NSDate *)targetDate {
         NSDate *date;
         NSRange tempRange;
         NSRange returnRange = [self firstEntryTitleRange];
         if (returnRange.location == NSNotFound)
                return NSMakeRange(NSNotFound, 0);
         do {
             date = [self dateFromEntryTitleRange:returnRange];
             tempRange = [self nextEntryTitleRangeForIndex:
                     returnRange.location + returnRange.length];
             if (tempRange.location == NSNotFound) break;
             if ((date == nil)
                     || ([date timeIntervalSinceDate:targetDate] < 0))
                     returnRange = tempRange;
         } while ((date == nil)
                || ([date timeIntervalSinceDate:targetDate] < 0));
         return returnRange;

    The method starts by declaring the date, tempRange, and returnRange local variables. It calls -firstEntryTitleRange to set returnRange to the first entry title in the diary, returning a range with location NSNotFound if the diary contains no entries. It then enters the loop, calling -nextEntryTitleRangeForIndex: to look for each successive entry title until it runs out of titles or finds one that is more recent than the target date. It calls a method that you have yet to write, -dateFromEntryTitleRange:, to convert each title to an NSDate object if possible. It ignores entry titles that are malformed, indicated by a nil date. When it runs out of entry titles or finds one that is more recent than the target date, it returns the range with the last qualifying date.

  3. Write the -dateFromEntryTitleRange: method. Once you've done this, the support methods for the -goToDatedEntry: action method will be complete.

    In the DiaryDocument.h header file, declare it immediately following the -firstEntryTitleRangeAtOrAfterDate: method:

    - (NSDate *)dateFromEntryTitleRange:(NSRange)range;

    Define it as follows in the same relative location in the DiaryDocument.m implementation file:

    - (NSDate *)dateFromEntryTitleRange:(NSRange)range {
         if ((range.location == NSNotFound)
                || (range.length < 2)) return nil;
         range.location += 2;
         range.length -= 2;
         NSString *dateString = [[[[self diaryView] textStorage]
                string] substringWithRange:range];
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                [formatter setDateStyle:NSDateFormatterLongStyle];
                [formatter setTimeStyle:NSDateFormatterLongStyle];
                NSDate *date = [formatter dateFromString:dateString];
                [formatter release];
                return date;

    This method returns a date derived from the title range in the range parameter. It returns nil if the incoming range value is an NSNotFound range, or if its length is less than 2. The length test is based on the fact that all entry titles begin with the entry marker character and a space; without those, the title can't hold a date. The test is necessary so that the immediately following range manipulations do not cause an error if the user has deleted all of the title string except the initial title marker.

    The method then adjusts the incoming range to eliminate from consideration the leading title marker and space.

    The rest of the title should be a human-readable date string using NSDateFormatter's NSDateFormatterLongStyle, but the user might have edited it so that it no longer represents a date that Cocoa can interpret. Fortunately, NSDateFormatter's -dateFromString: method returns nil if it is unable to read the string. After allocating and initializing a new formatter and setting its date and time styles, the method calls -dateFromString:, releases the formatter, and returns the date as an NSDate object.

  4. The -goToDatedEntry: action method will now work, once you connect it up in Interface Builder. However, you should take steps to disable the date picker when there are no entries in the diary. First, add this clause at the end of the -validateUserInterfaceItem: implementation in the DiaryWindowController.m source file:

    } else if (action == @selector(goToDatedEntry:)) {
         return [[self document] firstEntryTitleRange].location != NSNotFound;

    You call the existing -firstEntryTitleRange method for the test range because if there is no first entry, there is no entry at all.

    Next, declare a subclass of NSDatePicker called ValidatedDiaryDatePicker. This should be the same as the ValidatedDiaryButton subclass at the end of the DiaryWindowController files except that it inherits from NSDatePicker, not from NSButton. Declare it like this:

    @interface ValidatedDiaryDatePicker :
           NSDatePicker <VRValidatedControl> {

    Implement it exactly the same as the ValidatedDiaryButton's -validate method:

    @implementation ValidatedDiaryDatePicker
    - (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];

    You must also turn the date picker into a ValidatedDiaryDatePicker. Select the date picker in the diary window in Interface Builder, and then in the Validated Diary Date Picker identity inspector, choose ValidatedDiaryDatePicker as its class.

  5. The second task in this step is to tell the date picker what date to display while the user is editing or navigating in the diary. To do this, you must first write an outlet for the date picker to act as the receiver for the message.

    In the DiaryWindowController.h header file, add this declaration at the end of the instance variable declarations between the braces of the @interface directive:

    IBOutlet NSDatePicker *datePicker;

    Add this accessor method after the -otherDiaryView accessor:

    - (NSDatePicker *)datePicker;

    In the DiaryWindowController.m implementation file, add this implementation after the -otherDiaryView accessor:

    - (NSDatePicker *)datePicker {
         return [[datePicker retain] autorelease];

    Build the project, and then, in Interface Builder, Control-drag from the File's Owner proxy to the date picker in the diary window and choose datePicker from the Outlets section of the HUD.

  6. Next, write a method to update the date picker's displayed value based on the range of the current entry's title. Call it -updateDatePickerValue. In the DiaryWindowController.h header file, add the declaration after -updateWindow, as follows:

    - (void)updateDatePickerValue;

    Define it like this:

    - (void)updateDatePickerValue {
         NSRange range = [self currentEntryTitleRangeForIndex:
                 [self insertionPointIndex]];
         if (range.location == NSNotFound) {
             [[self datePicker] setDateValue:[NSDate date]];
         } else {
             [[self datePicker] setDateValue:
                    [[self document] dateFromEntryTitleRange:range]];

    If there is no current entry or the insertion point is in an untitled preface, the method sets the displayed value of the date picker to the current date and time, using NSDatePicker's -setDateValue: method. This happens both when a new, empty window is opened and when the user moves the insertion point into the preface.

    If there is a current entry, the method sets the date picker to display its title in the form of a date. If the date value of the current entry's title is nil because the user has edited it, nothing happens because -setDateValue: does not do anything with a nil parameter value.

  7. Finally, call the -updateDatePickerValue method every time the window updates. Add this statement at the end of the existing -updateWindow method implementation:

    if (![[[self window] firstResponder]
           isKindOfClass:[NSDatePicker class]]) {
        [self updateDatePickerValue];

    It is necessary to verify that the date picker does not currently have keyboard focus, because the date picker should not be updated automatically while the user is using it to set a date value.

  8. Open the DiaryWindow nib file in Interface Builder. Control-drag from the date picker in the diary window to the First Responder proxy in the DiaryWindow nib file's window, and then select the goToDatedEntry: action in the Received Actions section of the HUD. The date picker is now connected. Changing any of its values, such as the seconds, while the application is running executes the action method. This can have a highly interactive feeling in the date picker because, if you hold down the increment or decrement button to change the value continuously, the selection changes every time the value passes a threshold.

  9. Run the application and test the date picker. This requires patience, because it works to best advantage if a little time separates each entry. Taking your time, add three or four entries separated by at least several seconds. Then click in different entries at random, and confirm that the date picker changes to reflect the date and time of the current entry's title. Then click to select the seconds cell in the date picker, and click the increment and decrement buttons to change the time backward and forward. As you do this, watch the selection in the diary's text. It moves from title to title based on the principle that the first entry at or after the date set in the date picker is selected.

  • + 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