I have trouble creating a cleaning function for garbage collection [example inside]

advertisements

I'm trying to have a global cleanup function, and pass the MovieClip or TextField for removal. I want to remove the clip without referencing the clip directly. Any help would be greatly appreciated.

var clip:Sprite = new Sprite();
clip.graphics.beginFill(0x000000, 1)
clip.graphics.drawRect(0,0,100,100)
clip.graphics.endFill()
clip.name = "clip"
addChild(clip);

cleanup(clip)

function cleanup(mc):void {
    removeChild(mc.parent.getChildByName(mc.name));
    mc = null

    // clip is removed and traces as [object Sprite]
    trace(clip)

    //
    addChild(clip);
    removeChild(clip)
    clip = null

    // clip is removed and traces as null.
    trace(clip)
}

Here is the FLA (Flash cs4): http://dl.dropbox.com/u/4725599/test-cs4.zip


You seem to have a misunderstanding of scope. I'll try to explain what you're doing:

function cleanup(mc):void {
    removeChild(mc.parent.getChildByName(mc.name)); // removes the "clip" sprite
    mc = null; // nulls the local var "mc", which essentially does nothing

    addChild(clip);     // re-add the "clip" sprite
    removeChild(clip)   // remove the "clip" sprite
    clip = null;        // null the "clip" sprite, removing the last reference to the memory allocated for the sprite
}

Basically, when you create your Sprite, you're allocating the memory needed for a Sprite and assigning it to the clip variable. Your sprite now has one reference to it.

You then add it to the stage. This creates a new reference, so your sprite now has 2 references. That's it.

The mc variable in the cleanup() function is a temporary variable - they're cleaned up after the function exits so you don't need to worry about it. Basically to tag your Sprite for garbage collection, you need to remove the 2 references to it: the clip variable, and the stage. So you simply need to do:

clip.parent.removeChild( clip );
clip = null;

And it's done.

Check out that: http://divillysausages.com/blog/tracking_memory_leaks_in_as3 (disclaimer: my site) which should give you a good explanation of how memory works in as3

Edit Normally you would work this based on classes. In all my classes, I implement a destroy() function that I can call to clean up the class (remove children, event listeners, any references to other objects etc). For the code calling destroy(), it doesn't care what the object does or how it works, it just know that afterwards the object is good for garbage collection.

As a general principle, the object creating something is also responsible for destroying it.