现有事件侦听器是否阻止正确处理对象?

时间:2014-05-23 13:56:24

标签: actionscript-3 memory-management memory-leaks event-listener destroy

我有一个主课,另一个课说" A"。

public class A extends MovieClip
{
    private var z : int;
    private var y : String;

    public function A(param1 : int, param2 : String)
    {
        z = param1;
        y = param2
        Stage.addEventListener(eventString, functionToBeTriggered);
    }

    private function functionToBeTriggered(evt : EventType) : void
    {
       trace(z+"....."+y);
    }
}

我从Main Class创建了A类对象。我也正确处理这些物体。在A类中,我为Stage添加了一个事件监听器,当我处理A类对象时,我忘了将其删除。每当我从Main Class创建一个A类对象时,Stage上的监听器就会增加。在听力上执行的功能使用''并且' y'对象的变量。

这些是我使用的步骤: -

    1) I create an object say "objA" of Class A; Stage has 1 event listener.
    2) I dispose "objA"; but Stage still has 1 event listener.
    3) I create another object say "objB" of Class A; Stage now has 2 event Listeners.
    4) I dispatch the event to trigger functionToBeTriggered; Now 2 function are triggered one of objA and another of objB; I got 'z' and 'y' of both objA and objB

这些是我的疑惑: -

    1) As I have disposed objA before creating objB ie. I did objA = null; how did i get the value of 'z' and 'y' of objA?
    2) Is an active Listener preventing me from proper disposal of object?
    3) How do I clear references of primitive data types like int and String etc ?

我希望我已经清楚地表达了我的问题。请帮忙。

1 个答案:

答案 0 :(得分:2)

通过调用addEventListener,可以防止的实例超出范围并被销毁。通过谷歌搜索“as3垃圾收集”或类似内容了解更多相关信息。因此,您需要删除对您的实例的引用。

一般经验法则:每次执行“addEventListener”时,都应确保拥有适当的“removeEventListener”。

基本示例:

public class A
{
    public function A()
    {
        Stage.addEventListener(eventString, functionToBeTriggered);
    }

    function cleanup():void
    {
        Stage.removeEventListener(eventString, functionToBeTriggered);
    }
}

public class Foobar
{
    var a = new A();
    a.cleanup(); //by omitting this line, the instance 'a' cannot be garbage collected due to Stage holding a reference to that instance
}

关于您的其他问题:

  1. 您尚未处置objA,您只清除了一个参考 它,但不是addEventListener
  2. 中的依赖
  3. 不明白,但答案可能是“是”
  4. 原始数据类型与您的问题无关,它们只是数据而不是 参考