Apple WebObjects 3.5 User Manual

Page 173

Advertising
background image

WebScript Language Elements

173

aString = [NSString stringWithString:@"Fred"];

Note that a class is represented in a script by its corresponding class name—
in this example, NSString.

In WebScript, the classes you use include both class methods and instance
methods
. Most class methods create a new instance of that class, whereas
instance methods provide behavior for instances of the class. In the
following example, a class method,

stringWithFormat:

, is used to create an

instance of a class, NSString. Instance methods are then used to operate on
the instance

myString

:

// Use a class method to create an instance of NSString
NSString *myString = [NSString

stringWithFormat:@"The next word is %@", word];

// Use instance methods to operate on the instance myString
length = [myString length];
lcString = [myString lowercaseString];

In an Objective-C class definition, class methods are preceded by a plus
sign (+), while instance methods are preceded by a minus sign (-). You
cannot declare class methods in WebScript, but you can use the Objective-
C class methods defined for any class.

Creating Instances of Classes

The section “Variables” (page 166) told you how to declare variables, which
represent objects. Before you use a variable, you must first create the object,
or instantiate the class that defines the object. In WebScript, there are two
different ways to create objects. The first approach, which applies only to
the most commonly used classes, is to initialize with constant objects as
described in the section “Assigning Values to Variables” (page 168). The
second approach, which applies to all classes, is to use creation methods.

All classes provide creation methods that you can use to create an instance
of that class. Depending on the class and the particular creation method, the
instances of the class you create are either mutable (modifiable) or immutable
(constant). Usually, the instances of a class are always mutable or always
immutable. (You must read the specifications in the Foundation Framework
Reference
to find out if a particular class is immutable or mutable.) However,
some classes, including NSString, NSArray, and NSDictionary provide both
mutable and immutable forms, and you can choose which one to create. It’s
best to create immutable objects wherever possible. Use a mutable object
only if you need to change its value after you initialize it.

Here are some examples of using creation methods to create mutable and
immutable NSString, NSArray, and NSDictionary objects:

Advertising