Table of Contents Previous Section

Implement awake and sleep

The final step to creating the GuestBook application is to implement the methods awake and sleep. These two methods are standard methods that can be implemented in any component that needs them. awake is a method that sets up the component at the beginning of every transaction. sleep resets the component at the end of every transaction.

  1. Click the script button to display Main's script file.

  2. Add two more methods in the script window:
    - awake {
    	aGuest = [NSMutableDictionary dictionary];
    }

    - sleep {
    aGuest = nil;
    }

  3. Choose FileSave All to save all of the files in the application.
You're done writing the GuestBook application, so you can exit WebObjects Builder.

A closer look

The job of awake is to prepare the page for the current transaction. In Main's case, whenever a new transaction begins, there's a new user to add to the guest list. Therefore, Main needs to allocate a new, empty aGuest variable before the transaction begins. aGuest (and all other variables of type Guest) are really NSMutableDictionary objects. NSMutableDictionary is a class defined in the Foundation Framework. NSMutableDictionary objects have key-value pairs. (The class is called "mutable" because you can change the contents of the dictionary after you create it.)

After the awake method, WebObjects code takes the values from the form and assigns them to the attributes in the aGuest variable. By the time the submit method begins executing, aGuest contains the current guest's information.

The sleep method performs the inverse operation of the awake method. It essentially erases any temporary state the page had for this transaction. Because you created an empty aGuest variable in awake, you reset it to nil in sleep.

The sequence of events for a transaction in the GuestBook goes like this:

  1. The user clicks the Submit button.

  2. Main's awake method creates a new aGuest.

  3. WebObjects code populates aGuest's attributes (name, e-mail, and comments) with information the user entered on the page.

  4. The submit method adds aGuest to the end of the guest list.

  5. The WORepetition iterates through the guest list and displays the name, e-mail, and comments of each guest.

  6. Main's sleep method sets aGuest to nil.
To learn more about awake, sleep, and WebScript in general, see "Using WebScript" in the WebObjects Developer's Guide. To learn more about the Foundation Framework (where NSMutableDictionary is defined), see the Foundation chapter of the WebObjects Developer's Guide.

Table of Contents Next Section