Graphics Programs Reference
In-Depth Information
Using Instances
In order to use an instance of a class (an object), you must have a variable that points to the
object. A pointer variable stores the location of an object in memory, not the object itself.
(It “points to” the object.) A variable that points to an object is declared like so:
Party *partyInstance;
This variable is named
partyInstance
. It is meant to be a pointer to an instance of the
class
Party
. However, this does not create a
Party
instance - only a variable that can
point to a
Party
object.
Creating objects
An object has a life span: it is created, sent messages, and then destroyed when it is no
longer needed.
To create an object, you send an
alloc
message to a class. In response, the class creates
an object in memory and gives you a pointer to it, and then you store that pointer in a vari-
able:
Party *partyInstance = [Party alloc];
Here an instance of type
Party
is created, and you are returned a pointer to it in the vari-
able
partyInstance
. When you have a pointer to an instance, you can send messages
to it. The first message you
always
send to a newly allocated instance is an initialization
message. Although sending an
alloc
message to a class creates an instance, the instance
isn't valid until it has been initialized.
[partyInstance init];
Because an object must be allocated
and
initialized before it can be used, we always com-
bine these two messages in one line.
Party *partyInstance = [[Party alloc] init];
The code to the right of the assignment operator (
=
) says, “Create an instance of
Party
and send it the message
init
.” Both
alloc
and
init
return a pointer to the newly cre-
ated object so that you have a reference to it.