Subscribe to
Posts
Comments

I’ve been experience an unusual problem when working with singleton classes in the Flash IDE. When testing a movie and using the simulate download my singletons aren’t initalized corrected. The problem occurs because you can’t immiedetly test using simulate download, you first have to test the movie and then run it again to start the simulated download. It appears that the Flash IDE doesn’t reinstantiate static variables (like the ones used in singletons) and thus getInstance will return the singleton object created on the first test without actually reinstantiating the class. Its as if it returns an empty object. I have yet to find an acceptable solution for this, but have found a workaround.

I usually know which object will create the singleton class first, so by adding a boolean variable to the getInstance function I can tell it to call an init function regardless of whether or not you ran it in the intial test movie or the simulated download afterwords.

class com.dcholth.singleton.MySettings {
private static var __uniqueInstance:MySettings;

private var __myWebsite:String;
private var __myName:String;

private var __numberOfMySettings;

private function MySettings(){
init();
}

private function init(){
trace(“MySettings Created”);
__myWebsite = “http://www.dcholth.com/blog”;
__myName = “D.C. Holth”;

}

// Delete the else if when using in your final version in production
        public static function getInstance(firstInit:Boolean):MySettings{
if(__uniqueInstance == undefined){
__uniqueInstance = new MySettings;
} else if(firstInit){
init();
}
return __uniqueInstance;
}
}

Now when when the first MySettings object is being created I pass the the true parameter with the getInstance() function it will run the initialization functions. It is important that init is declared as private and that the ‘else if’ is removed from the getInstance when using in a production environment or you may experience problems.

Leave a Reply