目录

AnimatorResultNotRelease

通过Animator.create()、Animator.createAnimator()方法创建的AnimatorResult对象,使用完毕后,需及时调用finish()或cancel()方法释放对象,避免导致内存泄漏。

规则配置

// rules.json
{
  "rules": {
    "arkts": {
      "ResourceLeak": [
        {
          "ruleId": "AnimatorResultNotRelease",
          "severity": "error",
          "skip": false
        }
      ]
    }
  }
}

正例

import animator, { AnimatorOptions, AnimatorResult, SimpleAnimatorOptions } from '@ohos.animator';
let simpleOptions: SimpleAnimatorOptions = new SimpleAnimatorOptions(100, 200).duration(2000);

let options: AnimatorOptions = {
  duration: 1500,
  easing: "friction",
  delay: 0,
  fill: "forwards",
  direction: "normal",
  iterations: 3,
  begin: 200.0,
  end: 400.0,
};

/**
 * 正例:正确释放资源
 */
@Component
export struct TestRelease {
  private animator1: AnimatorResult = animator.create(simpleOptions);
  private animator2: AnimatorResult = animator.createAnimator(options);
  aboutToAppear() {
    console.log('Do something else');
  }
  build() {
    Text('Hello TestRelease')
  }
  aboutToDisappear() {
    this.animator1.cancel();
    this.animator2.finish();
  }
}

反例

import animator, { AnimatorOptions, AnimatorResult, SimpleAnimatorOptions } from '@ohos.animator';
let simpleOptions: SimpleAnimatorOptions = new SimpleAnimatorOptions(100, 200).duration(2000);

let options: AnimatorOptions = {
  duration: 1500,
  easing: "friction",
  delay: 0,
  fill: "forwards",
  direction: "normal",
  iterations: 3,
  begin: 200.0,
  end: 400.0,
};

/**
 * 反例:未释放资源
 */
@Component
export struct TestNotRelease {
  private animator1: AnimatorResult = animator.create(simpleOptions);
  private animator2: AnimatorResult = animator.createAnimator(options); // leak
  aboutToAppear() {
    console.log('Do something else');
  }
  build() {
    Text('Hello TestNotRelease')
  }
  aboutToDisappear() {
    this.animator1.cancel();
  }
}

Code Scanner代码检查规则的配置指导请参考1.6.3 代码检查工具(codescanner)