2012-03-15 97 views
3

中的嵌入式位圖資產首次在此處發佈。有沒有辦法清除AS3/AIR

我正在創建一個AIR 3.0應用程序。

對於我的很多圖形資源,我使用Flex嵌入的元數據將位圖對象嵌入爲類,然後實例化它們。

問題是,它似乎從來沒有收到垃圾。我沒有在網上找到很多信息,但我看過一些似乎證實這一點的帖子。

無論何時,我的一個類被實例化爲具有這些嵌入資源,它們總是創建Bitmaps和BitmapDatas的新實例,而不是重用已存在的內容。這是一個巨大的記憶問題。而且我找不到任何方式去取消它們或讓它們留下記憶。

所以我能想到的唯一解決方案就是從磁盤加載圖形而不是使用嵌入標籤。但我寧願不要這樣做,因爲應用程序打包和安裝時,所有這些圖形資產都將位於最終用戶計算機上,而不是包含在SWF中。

Anyoen碰到這個?有一個解決方案?或者我可以想到的替代解決方案?

謝謝! Kyle

回答

1

嗯,我想這是預期的行爲,因爲新的操作員應該總是創建新的對象。但是這些新對象應該被垃圾收集,只是資產類不會,因爲它是一個類。

您可以構建一個像單件工廠一樣的緩存。你通過指定一個id來請求你的圖像,然後緩存創建該圖像,如果它不存在,或者如果它返回單個實例。它已經有一段時間,因爲我最後一次編碼的ActionScript,所以也許你要以此爲僞代碼;)

public class Cache { 

    import flash.utils.Dictionary; 
    import flash.utils.getDefinitionByName; 

    [Embed(source="example.gif")] 
    public static var ExampleGif:Class; 

    /** 
    * The single instance of the cache. 
    */ 
    private static var instance:Cache; 

    /** 
    * Gets the Cache instance. 
    * 
    * @return 
    *  The Cache 
    */ 
    public static function getInstance():Cache { 
     if (Cache.instance == null) { 
      Cache.instance = new Cache(); 
     } 
     return Cache.instance; 
    } 

    /** 
    * The cached assets are in here. 
    */ 
    private var dictionary:Dictionary 

    public function Chache() { 
     if (Cache.instance != null) { 
      throw new Error("Can not instanciate more than once."); 
     } 
     this.dictionary = new Dictionary(); 
    } 

    /** 
    * Gets the single instantiated asset its name. 
    * 
    * @param assetName 
    *  The name of the variable that was used to store the embeded class 
    */ 
    public function getAsset(assetName:String):Object { 
     if (this.dictionary[assetName] == null) { 
      var AssetClass = getDefinitionByName(assetName) as Class; 
      this.dictionary[assetName] = new AssetClass(); 
     } 
     return this.dicionary[assetName]; 
    } 

} 

然後,您可以使用這樣的:

public class Example { 

    public static function main() { 
     Bitmap exampleGif1 = Cache.getInstance().getAsset("ExampleGif") as Bitmap; 
     Bitmap exampleGif2 = Cache.getInstance().getAsset("ExampleGif") as Bitmap; 
     trace("both should be the same instance: " + (exampleGif1 == exampleGif2)); 
    } 

} 

我沒有測試此,所以讓我知道它是否有效。

相關問題