2011-09-15 73 views
0

最初我有十個arraycollections在flex模塊中聲明,我認爲這導致了內存泄漏。所以我把它們分成了一個類,我使用我在裏面創建的「destroy」方法來清理它們。這會工作嗎?清潔ArrayCollections

我討厭問題標題不好意思。但我不會把它寫成像「引誘垃圾收集器」

 [Bindable] 
     public class Cfd 
     { 
      private static var instance:Cfd = new Cfd(); 
      private var _cfds:ArrayCollection = new ArrayCollection(); 

      // Constructor 
      public function Cfd(){ 
       if (instance) { throw new Error('Cannot create a new instance. Must use Cfd.getInstance().') } 
      } 

      public static function getInstance():Cfd{ 
       return instance; 
      } 

      public function get cfds():ArrayCollection{ 
       return _cfds; 
      } 
      public function set cfds(value:ArrayCollection):void{ 
       _cfds = value; 
      } 

      public function destroy():void{ 
       if(_cfds != null){ 
        _cfds.removeAll(); 
       } 
       } 
} 

回答

1

當你使用這樣的單身人士,你幾乎保證了內存泄漏,因爲你可能會從所有的地方聽的ArrayCollection(也許項目內的話)。當您通過getter/setter對明確提供對象的引用時,您可以將偵聽器添加到setter中,並在重置值時移除它。

查看http://www.developria.com/2010/08/rethinking-addeventlistener-an.html瞭解更多關於正在發生的事情。

更多關於爲什麼你應該避免單身http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars

+0

我必須給你提供關於單身人士的警告。謝謝。 – overmann

1

只是空對象應該這樣做,除非你有聽衆附加到它。

cfds = null; 

我從來沒有見過[Bindable]用於類本身,所以不知道你在那裏試圖做什麼。

package{ 
    public final class Cfd{ 
     private static var instance; 

     private var _cfds:ArrayCollection = new ArrayCollection(); 

     public function Cfd(singletonEnforcer:MySingletonEnforcer){ 
      if (instance) { throw new Error('Cannot create a new instance. Must use Cfd.getInstance().') } 
     } 

     public static function getInstance():Cfd{ 
      if (instance == null) 
      instance = new MySingleton(new MySingletonEnforcer()); 
      return instance; 
     } 

     // don't see a real need for setter/getters here 
     public static function get cfds():ArrayCollection{ 
      return _cfds; 
     } 
     public static function set cfds(value:ArrayCollection):void{ 
      _cfds = value; 
     } 

     // I wouldn't even use a destroy on this class since it is a singleton. 
     // just set the data to null Cfd.cfds = null 
     public static function destroy():void{ 
      _cfds = null 
     } 
    } 
    } 

    //this is in Cfd.as but is outside the package block 
    class MySingletonEnforcer {} 
+0

'[綁定]'上一流水平,使類可綁定的所有公共屬性。在這種特殊情況下,它與把它放在'cfds'屬性上完全一樣,因爲類中只有一個公共屬性。 – RIAstar

+0

啊我感謝您的意見。 –