Keep a Reference to Your Context or it will be Garbage Collected
When initializing a Context in AS3 you need to make sure to keep a reference to your context. This is wrong:
public class Main extends Sprite { public function Main() { var context:MyContext = new MyContext(this); } }
In the above code, the MyContext is created as a method scoped variable. It will be created, but at some point (in the very near future) it will be garbage collected. It is available for garbage collection on the next frame. You will likely see your application initialize, work for a few seconds, and then start throwing null (or other) errors. This can be avoided by keeping a class scoped variable reference to the context:
public class Main extends Sprite { private var context:MyContext; public function Main() { context = new MyContext(this); } }
Now the context will be held in memory until the context variable is set to null. Note that this also applies to initializing a Context within a Flex application in an MXML script block.