beautypg.com

Apple WebObjects 3.5 User Manual

Page 167

background image

WebScript Language Elements

167

In these declarations,

id

is a data type. The

id

type is a reference to any

object—in reality, a pointer to the object’s data (its instance variables). Like
a C function or an array, an object is identified by its address; thus, all
variables declared in WebScript are pointers to objects. In the examples
above,

myVar1

and

myVar2

could be any object: a string, an array, or a custom

object from your application.

Note:

Unlike C, no pointer manipulation is allowed in WebScript.

Instead of using

id

, you can specifically refer to the class you want to

instantiate using this syntax:

className

*

variableName

;

For example, you could specify that a variable is an NSString object using
this syntax:

NSString *myString1;
NSString *myString1, *myString2;

For more information on specifying class names in variable declarations, see
the section “Data Types” (page 174).

In WebScript, there are two basic kinds of variables: local variables and
instance variables. You declare instance variables at the top of the file, and
you declare local variables at the beginning of a method or at the beginning
of a block construct (such as a

while

loop). The following shows where

variables can be declared:

id instanceVariable; // An instance variable for this class.

- aMethod {

id localVariable1; // A local variable for this method.

while (1) {

NSString *localVariable2; // A local variable for this block.

}

}

Variables and Scope

Each kind of variable has a different scope and a different lifetime. Local
variables are only visible inside the block of text in which they are declared.
In the example above,

localVariable1

is declared at the top of a method. It is

accessible within the entire body of that method, including the

while

loop. It

is created upon entry into the method and released upon exit.

localVariable2

,

on the other hand, is declared in the

while

loop construct. You can only access

it within the curly braces for the

while

loop, not within the rest of the method.