Graphics Programs Reference
In-Depth Information
Destroying objects
To destroy an object, you set the variable that points at it to
nil
.
partyInstance = nil;
This line of code destroys the object pointed to by the
partyInstance
variable and
sets the value of the
partyInstance
variable to
nil
. (It's actually a bit more complic-
ated than that, and you'll learn about the details of memory management in the next
chapter.)
The value
nil
is the zero pointer. (C programmers know it as
NULL
. Java programmers
know it as
null
.) A pointer that has a value of
nil
is typically used to represent the ab-
sence of an object. For example, a party could have a venue. While the organizer of the
party is still determining where to host the party,
venue
would point to
nil
. This allows
us to do things like so:
if (venue == nil) {
[organizer remindToFindVenueForParty];
}
Objective-C programmers typically use the shorthand form of determining if a pointer is
nil
:
if (!venue) {
[organizer remindToFindVenueForParty];
}
Since the
!
operator means “not,” this reads as “if there is not a venue” and will evaluate
to true if
venue
is
nil
.
If you send a message to a variable that is
nil
, nothing happens. In other languages,
sending a message to the zero pointer is illegal, so you see this sort of thing a lot:
// Is venue non-nil?
if (venue) {
[venue sendConfirmation];
}
In Objective-C, this check is unnecessary because a message sent to
nil
is ignored.
Therefore, you can simply send a message without a
nil
-check:
[venue sendConfirmation];