close

Filter

loading table of contents...

Studio Developer Manual / Version 2401

Table Of Contents

8.3.3.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:

class MyComponent extends Component {

  #foo:SomethingExpensive;

  constructor(config:Config<MyComponent> = null) {
    super(config);
    this.#foo = new SomethingExpensive();
  }

  protected onDestroy():void {
    this.#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:

class MyComponent extends Component {

  #foo:SomethingExpensive;

  constructor(config:Config<MyComponent> = null) {
    super(config);
    this.#foo = new SomethingExpensive();
    this.addListener("timeout", this.#handleTimeout);
  }

  #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 (this.#foo) {
      this.#foo.doSomething();
    }
  }

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

Search Results

Table Of Contents
warning

Your Internet Explorer is no longer supported.

Please use Mozilla Firefox, Google Chrome, or Microsoft Edge.