开发者

Actionscript 3: Do you need to remove EventListeners?

In actionscript 3, I dynamically create objects to which I add EventListeners. These objects are added to arrays and might be removed again later. And others might be added later again. Each time I create an object, I add these EventListeners to them. However, is it necessary to remove these event listeners too, when deleting these objects? What happens when I lose all references to an object but don't delete these EventListeners? Do they st开发者_StackOverfloway somewhere in the memory, unreachable and unusuable, or does the GC clean them up?


Yes, you have to remove event listeners if you are not using weak references. GC won't clean up an object if there is a reference to it, and registering event listeners do create a reference to the object unless you set the useWeakReference parameter (the 5th parameter to the addEventListener method) to true while registering the event listener. Weak references won't be counted by the garbage collector.

//Using strong reference: needs to be removed by calling removeEventListener
sprite.addEventListener(Event.TYPE, listenerFunction, useCaptureBool, 0, false);

//Using a weak reference: no need to call removeEventListener
sprite.addEventListener(Event.TYPE, listenerFunction, useCaptureBool, 0, true);


When you have event listeners on an object you won't ever loose all references to it, so it'll stay in memory indefinitely. You need to make sure you always remove any listeners you set. You can set them using weak references, but that's not really a solution, it's better to remove them explicitly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜