Tuesday, July 22, 2008

Strange type casting behavior in AS3 when working with parent/child SWF loading.

So I finally solved a little issue I was having with AS3, type casting, and child SWF loading.

Situation: I had a child SWF (C) of custom type com.foo.SomeClass that had its own member variables, etc. I also had a parent SWF (B) that loaded in (C) using the normal loader.content object. Once loaded, this object was cast as type (C).

When I then tried to load (B) into a new parent shell SWF (A), the type cast operation that occurred in (B) on (C) would fail with the error:

TypeError: Error #1034: Type Coercion failed: cannot convert com.foo::SomeClass@34d1d31 to com.foo.SomeClass.

even when inspecting the object to be converted shows that it is an object of type SomeClass:

> someObj: [object SomeClass]

Solution: It turns out that the reason (B) wasn't failing at the type cast operation was because it had its own local variable of type SomeClass defined as part of the type cast operation logic.

Parent SWF (A) did not have this type defined anywhere, either public or private within its own class definition.

Once I added a local variable of type SomeClass within the parent SWF (A) the problem went away.

This has some strange consequences since a parent SWF may simply be implemented as a type of generic "shell" if you will. It may not really need to care about what goes on within its children or children of children that it may be loading.

Based on this behavior, it would seem that the topmost parent SWF would need to have variables defined of all of the possible types that may be used in casting behavior within its children up front.

If anyone has any suggestions/tips on how to prevent having to have the topmost parent SWF from having declared variables of types matching those that may be used in casting operations within child SWFs, I would be happy if you could send me a note.



Kris said...

I know this is an old post, but just for posterity, look into using the LoaderContext class to set what ApplicationDomain to load the child's classes into.

A good solution to your issue, is to try loading the child swf into ApplicationDomain.currentDomain.