• 写AS3需要养成好的编码习惯 [返回文章列表]     发表于: 2009-6-9  665人(次)浏览
  • 因为AS3的垃圾回收是自动的,如果你某个对象存在被引用,或者有没有被清除的事件侦听,当你unload 和 removedChild时都不能彻底的从内存中移除它。

    所以我们在写代码的时候一定要记得:

    声明了一个变量或引用要记得及时清空,如:

    var _mc=_movieClip

    ......

    _mc=null

    如果有一个数组,里面保存的是许多其他对象的引用,那么光设置这个数组为null是不行的,还要设置其每一个元素的值也为空arr[i]=null,比如

    var _arry:Array=new Array()

    for(var i=0;i<_mc.numChildren;i++){

    var _mc=_mc.getChildAt(i) as MovieClip

    arry.push(_mc)

    }

    clear:

    for(var i=0;i<_arry.length;i++){

     _arry[i]=null

     

    }

    _arry=[]

     

    2、事件侦听也要及时清除。

    具体看一段代码片段:

      private function removeSelf(e:Event) {
       trace("remove me now....")
       removeEventListener(Event.ADDED_TO_STAGE, addStage)
       stage.removeEventListener(gamestate.GAMEBOX_NOTICE_CLOSED, toReady)
       removeEventListener(Event.REMOVED_FROM_STAGE, removeSelf)
        _lostTimer.removeEventListener(TimerEvent.TIMER, setLeftTime)
        try{
        new LocalConnection().connect("foo");
        new LocalConnection().connect("foo");
       }catch(error : Error){
       }
     
        System.gc();
     
      }

     addEventListener(Event.REMOVED_FROM_STAGE,removeSelf)//当元件被移除舞台时

    3、还有强制垃圾回收。

     try{
        new LocalConnection().connect("foo");
        new LocalConnection().connect("foo");
       }catch(error : Error){
       }
     
        System.gc();
     
      }

    作者:翼 BLOG:www.ourbrander.com 

写AS3需要养成好的编码习惯 [返回文章列表]