destroy displayObject from stage and garbage collector as3?

176 views Asked by At

I need help with something very interesting. I try to remove child from parent or fro stage dinamicly but not just removeChild and I want to destroy entire object. Here is very simple example what I want to do.

public function TestProject()
    {
        holder = new Sprite();
        this.addChild(holder);

        object1 = new Sprite();
        object1.name = "object1";
        object1.graphics.beginFill(0x6daeff);
        object1.graphics.drawRect(0,0,100,100);
        holder.addChild(object1);

        stage.addEventListener(MouseEvent.CLICK,onClick);
    }

    protected function onClick(event:MouseEvent):void
    {
        var tmp:DisplayObject = holder.removeChild(object1);
        tmp = null;

       // holder.removeChild(object1) = null; this give me error. 
    }

//with this code object1 was removed from stage but object1 is not null. When I debug

object1 = flash.display.Sprite ; etc.

I want to remove child and at the same this child to be null. Any ideas...

3

There are 3 answers

0
am0wa On

To clean up memory you have to destroy all references to your object. In this case:

protected function onClick(event:MouseEvent):void
{
   if (holder.contains(object1))
       holder.removeChild(object1);
   object1 = null;
}

or

protected function onClick(event:MouseEvent):void
{
   if (object1.parent)
      object1.parent.removeChild(object1);
   object1 = null;
}

Note: When you'd applied null to local variable tmp you didn't affect the object1 instance variable.

1
BigApp7e On

Thanks for your answer but the point is in this example I write just one object. I Ask when I have 100 object for example. Something like this:

for(var i:int=0;i<holder.numOfChilder;i++)
{
    holder.getChildAt(i).addEventListener(Event.MouseEvent,onObjectClick)
}

function onObjectClick():void
{
   holder.removeChild(event.currentTarget as DisplayObject) = null;
}

child object are dynamic created and I want dynamic removed

0
am0wa On

To cleanup object that was created dynamically and to which you have no reference variable, just remove all event listers to it, to make it eligible for GC:

function onObjectClick(event:MouseEvent):void
{
   var target:DisplayObject = (event.currentTarget as DisplayObject); 
   target.removeEventListener(MouseEvent.CLICK, onObjectClick);
   holder.removeChild(target); 
}

Note: there is no need to set null to you local variable cause it will die automatically since method run will be finished

Note2: u can set useWeakReference=true during adding your listener to allow your listener being garbage-collected automatically.