清理ArrayCollections

时间:2011-09-15 22:49:50

标签: actionscript-3

最初我在flex模块中声明了十个arraycollections,我认为这会导致内存泄漏。所以我将它们分成一个类,我会使用我在其中创建的“destroy”方法进行清理。这会有用吗?

我讨厌问题标题,对不起。但我不会像“诱惑垃圾收集器”那样写它

        [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();
                }
                }
}

2 个答案:

答案 0 :(得分: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 {}

答案 1 :(得分:1)

每当你使用像这样的Singletons时,你几乎可以保证内存泄漏,因为你可能正在从所有地方收听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

的更多信息