Removing Tween For Garbage Collection in AS3
I'm trying to remove a tween
object after it has complete so the memory can be freed by garbage collection.
In this example I'm passing the fadeIn
function a UILoader
object that is cast as a sprite so that it fades in when it is finished loading. When the tween
finishes animating, I want to remove the tween
object. I've included the compiler errors as comments.
functio开发者_高级运维n fadeIn(e:Sprite):void
{
var myTween:Tween = new Tween(e, "alpha", None.easeNone, 0.0, 1.0, 0.2, true);
myTween.addEventListener(Event.COMPLETE, deallocateObject, false, 0, true);
}
function deallocateObject(e:Event):void
{
//delete(e.currentTarget); //Warning: 3600: The declared property currentTarget cannot be deleted. To free associated memory, set its value to null.
e.currentTarget = null; //1059:Property is read-only.
}
First of all, you want to use a TweenEvent to handle the completion of the tween. The currentTarget property of Event is read-only, so you need to "get" the current target from the event and cast it as a tween, then remove your event and set it to null:
// assuming MC on stage with instance name "test"
import fl.transitions.*;
import fl.transitions.easing.*;
function fadeIn(e:Sprite):void
{
var myTween:Tween = new Tween(e, "alpha", None.easeNone, 0.0, 1.0, 1, true);
myTween.addEventListener(TweenEvent.MOTION_FINISH, deallocateObject, false, 0, true);
}
function deallocateObject(e:TweenEvent):void
{
var myTween:Tween = e.currentTarget as Tween;
// -- I always remove even when using weak listeners
myTween.removeEventListener(TweenEvent.MOTION_FINISH, deallocateObject);
myTween = null;
}
fadeIn(test);
Watch out when using local Tweens inside a function. Often they will get garbage collected before the tween completes. You'll have to declare the tween as a class property instead if that happens. I recommend saving yourself some headache and using Tweener, gTween, et al. The Tween class sucks.
function fadeIn(e:Sprite):void
{
var myTween:Tween = new Tween(e, "alpha", None.easeNone, 0.0, 1.0, 0.2, true);
myTween.addEventListener(TweenEvent.MOTION_FINISH, deallocateObject);
}
function deallocateObject(e:Event):void
{
delete(e.currentTarget as Tween);
}
This works.
精彩评论