views:

289

answers:

2

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.

function 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.
 }
+1  A: 
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.

Pythovore
*facepalm* thanks :)
TheDarkInI1978
+1  A: 

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.

Typeoneerror
thanks. this is enlightening. however, i'm curious why you've imported both import fl.transitions.*; and then import fl.transitions.easing.*; is the second import necessary since you're imported all transitions already with the first import?
TheDarkInI1978
also, should deallocateObject's argument be e:Event or e:TweenEvent, or doesn't it matter?
TheDarkInI1978
[EDIT] oh, i just realized the asterisk from fl.transitions doesn't import easing. nevermind.
TheDarkInI1978
@Chunk1978. It should be TweenEvent but it also shouldn't matter since TweenEvent probably extends Event. Edited.
Typeoneerror