Previous to AIR 3, if a developer wanted to remove all children from a container object, it was necessary to first determine how many children were present through DisplayObjectContainer.numChildren
and then loop over each of these child objects, removing them one at a time.
With the DisplayObjectContainer.removeChildren()
method, one simple command can be used to remove all children of a parent container, making them all available for garbage collection.
You’ll want to be sure to remove any event listeners or other references to these children before invoking removeChildren
, else the garbage collector may not be able to totally free the memory allocated to these objects.
In the following example, we will generate a number of dynamic MovieClip
symbols upon the Stage
. We add an event listener to the Stage
as well, listening for a simple MouseEvent.CLICK
event – which then invokes a method to remove all of these MovieClips
with one simple command: stage.removeChildren()
.
package {
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.MouseEvent;
[SWF(width="600", height="500", backgroundColor="#CCCCCC")]
public class RemoveAllChildren extends Sprite {
public function RemoveAllChildren() {
generateDisplayObjects();
}
protected function generateDisplayObjects():void {
for(var i:int=100; i>0; i--){
var childMC:MovieClip = new MovieClip();
var randX:Number = Math.floor(Math.random() * (1+stage.stageWidth-100)) + 50;
var randY:Number = Math.floor(Math.random() * (1+stage.stageHeight-100)) + 50;
var randD:Number = Math.floor(Math.random() * 50-10) + 10;
childMC.x = randX;
childMC.y = randY;
childMC.graphics.beginFill(0x000000, 0.5);
childMC.graphics.drawCircle(0, 0, randD);
childMC.graphics.endFill();
this.addChild(childMC);
}
stage.addEventListener(MouseEvent.CLICK, removeAllChildren);
}
protected function removeAllChildren(e:MouseEvent):void {
stage.removeChildren();
}
}
}