Monday, March 4, 2013

Flash Builder: Building Crashes Player - Vector Issue

Problem:
While working with some vectors in AS3, I was in a hurry and typed out my vectors like this:

private var image_types:Vector.<String> = new Vector.<String>("png",'jpg','jpeg','gif');

This caused the Flash Player to crash without giving an error and needless to say, I had to reverse my steps until I figured out it was this Vector that was the problem.

Solution:
In the code I displayed above, I assumed that I could define some elements on Vector construction like you can with the Array class. This assumption is what caused the problem and ultimately a bug that isn't isn't caught when compiling the code down, but unexpectedly caught on execution. The Vector class doesn't allow you to pass list items into the constructor, but instead allows you to pass an uint and a Boolean which tell it what length to have and if it should be fixed.

The solution was simple enough though, using the Vector global function, I was able to modify my code slightly and have it compile and execute as expected.

private var image_types:Vector.<String> = new Vector.<String>(["png",'jpg','jpeg','gif']);

3 comments:

Unknown said...

you can initialize a Vector this way :

private var image_types:Vector. = new ['png','jpg','jpeg','gif'];

Unknown said...

You will have to leave out "new" to get that working:
private var image_types:Vector. = Vector.(["png",'jpg','jpeg','gif']);

Michael Corrigan said...

@Marcel, Good call! Vector is a global function, not a class type although I think you can keep the vector strict typed. For some reason, it is working for me with the new keyword...

@Khaled, I've never tried to initialize a vector this way, good to know! Thanks!