Table of Contents Previous Section

Accessing and Sharing Variables

WebScript automates the process of accessing non-local variables, whether they're declared in an application script, a session script, or in a component script. For a non-local variable myVar, for example, you can set and return its value from the script that declares it, as follows:

[self myVar];
[self setMyVar:newValue];

You don't have to implement these methods to invoke them---WebScript does this work behind the scenes. For example, you may notice that the Visitors Application.wos script doesn't implement visitorNum, setVisitorNum:, or setLastVisitor: methods, yet the Main.wos script invokes them.

In these statements:

[self myVar];
[self setMyVar:newValue];

the myVar and setMyVar: messages are sent to self, which indicates that the variable myVar is declared in the script that's accessing it. Sometimes a component script has to access application or session variables declared elsewhere. When you work with application and session variables, remember that they're owned by the application and session objects, respectively. To set or return their values, you send a message to the appropriate object, which, from a component script, you can always get by sending application or session to self. For example, the Main.wos script in the Visitors example includes these statements:

number = [[self application] visitorNum];
[[self application] setVisitorNum:number];    
[[self application] setLastVisitor:[[self application] aName]];

Note: The application object is also represented by the global variable WOApp. However, use of WOApp is discouraged because global variables are not permitted in some of the languages supported by WebObjects.

You can also access a non-local variable declared in one component script from another component script. This is something you commonly do right before you navigate to a new page, for example:

id anotherPage = [[self application] pageWithName:@"Hello"]; 
[anotherPage setNameString:newValue];

The current script uses the statement [anotherPage setNameString:newValue]; to set the value of nameString, which is declared in the page entitled "Hello".

This example uses the pageWithName: method, which takes the name of a page as an argument and returns that page. You most commonly use pageWithName: inside a method that returns a new page for display in the browser. Such a method could be associated with a hyperlink or a submit button. For example:

- contactPsychicNetwork
    id nextPage;
    nextPage = [[self application] pageWithName:@"Predictions"]; 
    return nextPage;

Table of Contents Next Section