第一次在这里发帖。
我正在创建一个 AIR 3.0 应用程序。
对于我的很多图形 Assets ,我使用 Flex 嵌入元数据将位图对象嵌入为类,然后实例化它们。
问题是这些似乎永远不会被垃圾收集。我没有在网上找到太多信息,但我看到了一些似乎证实了这一点的帖子。
每当我的一个类被实例化并具有这些嵌入式 Assets 时,它们总是会创建 Bitmaps 和 BitmapDatas 的新实例,而不是重用内存中已经存在的内容。这对内存来说是个大问题。而且我找不到任何取消引用它们或让它们留下内存的方法。
所以我能想到的唯一解决方案是从磁盘加载图形而不是使用嵌入标签。但我不想这样做,因为当应用程序被打包和安装时,所有这些图形 Assets 都将位于最终用户的计算机上,而不是包含在 SWF 中。
有人遇到这个吗?有解决办法吗?还是我能想到的替代解决方案?
谢谢!
凯尔
最佳答案
好吧,我想这是预期的行为,因为 new 运算符应该始终创建新对象。但是这些新对象应该被垃圾收集,只是 Assets 类不会,因为它是一个类。
您可以构建一个类似于单例工厂的缓存。您通过指定一个 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));
}
}
我没有测试这个,所以让我知道它是否有效。
关于actionscript-3 - 有没有办法清除 AS3/AIR 中的嵌入式位图 Assets ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9726142/