Quiz #1: Find the bug
Where is the bug in this program? It seems to run just fine. But there is a bug. Can you find it?
package { import flash.display.Sprite; import flash.events.Event; public class MyClass extends Sprite { public function MyClass() { this.addEventListener(Event.ENTER_FRAME, function(e:Event):void { trace("enter frame") }, false, 0, true); } } }
Comments(6)
The last arg–true–tells the event publisher to hold a weak reference to the callback function. So the in-line callback function might get garbage-collected.
Right?
Sprite has no idea what a frame is… since it’s a Sprite. So it won’t have an "enter frame" event. Am I right or am I right? Right?! Riiiiiight! :)
Sprite has no timeline, thus this makes no sense because enter frame event is never fired.
I’m thinking that using an inline function instead of a function call (as the eventListener) will make the listener unable to be removed.
A function is created and a reference to that function is passed to addActionListener, but the MyClass itself never saves a reference to the function. The last argument to addActionListener tells the event dispatcher to retain only a weak reference to the function. As a result, there are zero strong references to the function and it may be garbage collected at some point in the future. The trace() statement may print never, a few times, or forever- that is undefined and depends on the player’s garbage collection, which is outside of our control as SWF developers.
[...] Mike Morearty’s blog Mostly about the debugger in Adobe Flex Builder. « Quiz #1: Find the bug [...]