loading table of contents...

6.4.4.3. Memory Leaks Caused by Other References

Any reference to an object can cause it to stay alive. Thus, to find unwanted retainers, it makes sense to null-out all references a component keeps in its onDestroy() method, like in this code sketch:

public class MyComponent extends Component {

  private var foo:SomethingExpensive;

  public function MyComponent(config:myComponent) {
    super(config);
    foo = new SomethingExpensive();
  }

  protected function onDestroy():void {
    foo = null;
    super.onDestroy();
  }
}

You have to be careful that even after your component has been destroyed, certain asynchronous event callbacks may occur. Your event handlers have to be robust against fields already being null. Consider this example using a fictitious timeout event:

public class MyComponent extends Component {

  private var foo:SomethingExpensive;

  public function MyComponent(config:myComponent) {
    super(config);
    foo = new SomethingExpensive();
    addListener("timeout", handleTimeout);
  }

  private function handleTimeout():void {
    // Although we remove the listener in onDestroy,
    // an event may already be underway, so foo may
    // already be null in time it arrives: 
    if (foo) {
      foo.doSomething();
    }
  }

  protected function onDestroy():void {
    removeListener("timeout", handleTimeout);
    foo = null;
    super.onDestroy();
  }
}