Eliad Barazi
Eliad Barazi

Reputation: 25

Avoid null object reference errors in code inside the child SWF

I'm creating a global loader that loads different SWFs.
I don't have access to the child SWFs code.
I'm trying to avoid null object reference errors in code inside the child SWF that may reference "stage" etc.
I've added all the possible event listeners, added try/catch, tried all the applicationDomains and LoaderContexts permutations. for example:

applicationDomain = new ApplicationDomain(ApplicationDomain.currentDomain);
var con:LoaderContext = new LoaderContext(false, applicationDomain );
con.allowCodeImport = true;
var _loader:Loader = new Loader();
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoad);
_loader.load( new URLRequest(fileName + ".swf"), con);

I just can't catch the error or disable/remove the code from such a SWF.
for example, the following Main class:

package  {

    import flash.display.MovieClip; 
    public class Main extends MovieClip {   

        public function Main() {
            var h = this.stage.stageHeight;
            trace(h);
        }
    }
}

will crush any SWF that will try to load it as part of another SWF.

TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Main()

Any help with catching the Error, disabling/removing the code or any other idea will be much appreciated.
Thanks.

Upvotes: 1

Views: 137

Answers (1)

Jezzamon
Jezzamon

Reputation: 1491

Do you have access to the code in the child swf files? If so, you can do something like this:

package  {

    import flash.display.MovieClip; 
    public class Main extends MovieClip {   

        public function Main() {
            if (stage) {
                init();
            }
            else {
                addEventListener(Event.ADDED_TO_STAGE, init);
            }

        }

        public function init(evt:Event = null):void {
            removeEventListener(Event.ADDED_TO_STAGE, init);

            // You can now access the stage here
        }
    }
}

This will hold off initializing the child object until the stage reference is set. For all child objects the constructor will be called first before the stage is set, so you can't rely on it being there in the constructor.

Upvotes: 3

Related Questions