I’m having difficulty understanding what I expect to be a basic principle in memory management. Hopefully someone can offer an explanation that will help me better understand.
I have declared a single class variable ‘slideShow’.
var slideShow:SlideShow;
function addSlideShow(e:MouseEvent):void {
slideShow = new SlideShow();
addChild(slideShow);
}
function clearSlideshow (e:MouseEvent):void {
removeChild(slideShow);
}
If I call the function addSlideShow twice, two instances of the SlideShow class will be created and added to the stage.
If I call clearSlideshow twice, only one instance is removed from the stage. The second call creates an error.
I’m thinking that each time I call addSlideShow, the variable slideShow would be overwritten with the new instance of SlideShow, therefore only one instance would ever be created. This is obviously not the case.
With that in mind, is the following the correct way to handle things, where I remove and null the slideShow variable before creating a new instance?
var slideShow:SlideShow;
function addSlideShow(e:MouseEvent):void {
try {
removeChild(slideShow);
slideShow = null;
} catch (e:Error) {
trace(e);
}
slideShow = new SlideShow();
addChild(slideShow);
}
function clearSlideshow (e:MouseEvent):void {
try {
removeChild(slideShow);
slideShow = null;
} catch (e:Error) {
trace(e);
}
}
Thanks for any help you can offer.
The variable doesn’t get overwritten. There is a difference between the objects you create with
newand the referenceslideShowwhich is set to point to the first slide show object and then is set to point to the second one. What’s happening here, is that you don’t have any direct reference to the first object anymore, so you can’t remove it like you try to do. There still is a reference somewhere of course, as the object are children of the stage. So they won’t be garbage collected.Common solution is to use an array and push all instances in it, so you have a reference to remove them later.
In your case, you could also use the event’s target to remove an instance.