PersistentStorage:持久化存储UI状态
PersistentStorage将选定的AppStorage属性持久化存储,保留在设备磁盘上,在应用重新启动时能够获取到应用关闭时的状态
UI和业务逻辑不直接访问PersistentStorage中的属性,应用开发通常通过AppStorage访问PersistentStorage
PersistentStorage不允许的类型和值有
- 不支持嵌套对象(对象数组,对象的属性是对象等)。因为目前框架无法检测
AppStorage中嵌套对象(包括数组)值的变化,所以无法写回到PersistentStorage中 - 持久化数据是一个相对缓慢的操作,应用程序应避免以下情况
- 持久化大型数据集,最好是小于2kb的数据
- 持久化经常变化的变量
// 应用程序中的可选单例,直接使用
// 应用启动时,先判断PersistentStorage中是否有aProp属性,如果没有则在AppStorge中创建aProp值为47,并且PersistentStorage将值持久化存储;如果有则使用获取到的值在AppStorge中创建aProp
PersistentStorage.persistProp('aProp', 47);
@Entry
@Component
struct Index {
// 过AppStorage访问PersistentStorage
@StorageLink('aProp') aProp: number = 48
build() {
Row() {
Column() {
// 应用退出时会保存当前结果。重新启动后,会显示上一次的保存结果
Text(`${this.aProp}`)
.onClick(() => {
this.aProp += 1;
})
}
}
}
}