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:
Basically, when you create your
Sprite, you’re allocating the memory needed for aSpriteand assigning it to theclipvariable. 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
mcvariable in thecleanup()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 yourSpritefor garbage collection, you need to remove the 2 references to it: theclipvariable, and the stage. So you simply need to do: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 callingdestroy(), 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.