
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
ImageViewer Implementation (Take 3)
|
151
Incidentally, the name “destroy” is arbitrary. We could have synonymously used
“die,” “kill,” or “remove” with the same effect.
Finally, it’s worth noting that the
imageLoader listener list issue is not a particularly
unique situation. Any time an object is registered as a listener of another object, it
must be unregistered before being deleted. Example 5-7 shows the danger of not
unregistering an object before deleting it.
Try the following:
1. Place the Example 5-7 code on frame 1 of a movie.
2. Run the movie in Test Movie mode (Control
➝ Test Movie).
3. Click the Stage.
You should see “The mouse was pressed.” appear in the Output panel, even though
the object
obj was deleted! The reference to the object in the variable obj may have
been deleted, but another reference continues to exist in the Mouse object’s list of lis-
tener objects. To safely delete the object
obj, first unregister it as a Mouse listener, as
follows:
Mouse.removeListener(obj);
delete obj;
This section discussed one specific case in which an object reference
might inadvertently persist after deleting an instance of a class. Failure
to free up resources results in memory waste, which over time could
hinder performance or cause an application to fail. When you write a
class, you should ...