Call dispose() in a timely manner after use to release references to the real node for ComponentContent objects created via the constructor (which use BuilderNode underneath), and prevent memory leaks.
// rules.json
{
"rules": {
"arkts": {
"ResourceLeak": [
{
"ruleId": "ComponentContentNotRelease",
"severity": "error",
"skip": false
}
]
}
}
} import { ComponentContent } from '@kit.ArkUI';
@Builder
function buildText() {
Text('buildText')
}
/**
* Positive example: Resources are correctly released.
*/
@Component
export struct TestRelease {
private content: ComponentContent<Object> | null = null;
aboutToAppear() {
this.content = new ComponentContent<Object>(this.getUIContext(), wrapBuilder(buildText));
}
build() {
Text('Hello TestRelease')
}
aboutToDisappear() {
this.content?.dispose();
}
} import { ComponentContent } from '@kit.ArkUI';
@Builder
function buildText() {
Text('buildText')
}
/**
* Negative example: Resources are not released.
*/
@Component
export struct TestNotRelease {
private content: ComponentContent<Object> | null = null;
aboutToAppear() {
this.content = new ComponentContent<Object>(this.getUIContext(), wrapBuilder(buildText)); // leak
}
build() {
Text('Hello TestNotRelease')
}
aboutToDisappear() {
console.log('Do nothing');
}
} For details about how to configure Code Scanner check rules, see Using codescanner.