I load into an empty movieclip (via addChild) a library object (a movieclip of class MyObject that extends the MovieClip class). At some point, from the main I remove this custom movieclip from its parent and I set any reference to null to completely destroy it. The question: what if in the custom movieclip class there are eventListeners? Are them deleted when I destroy the object? Should I write a method to remove them before deleting the object?
3 Answers
Ideally, you should clean up all the internal references in in object if you are trying to destroy it for garbage collection purposes. You can also create your listeners with weak references to make them auto-destroy by passing the fifth argument as true
, but I personally recommend not using weak references and getting into the habit of properly cleaning up manually.
//setting a weak referenced listener
foo.addEventListener(Event.WHATEVER,bar(),false,0,true);
I include some type of destroy()
method in just about every class I write. This method is responsible for all instances of or references to any child objects in that class. This includes any listeners, display list references etc. Then, before I go to remove/null the parent, I call its destroy()
method to assure proper GC and avoid memory leaks. Note that this can chain down deeply nested objects, if need be.
You could just use weak references and remove the whole object. ASVM2 is generally smart enough to properly kill child objects BUT this is poor GC management, at best, and you are just asking for memory leaks.
My $.02.