HarmonyOS 关于数据持久化的咨询?

关于数据持久化的咨询 咨询场景描述: @StorageLink标记的持久化数据变量,是否会在修改变量值时自动将新数据保存到硬盘中?如何修改和保存持久化数据?

阅读 570
1 个回答

可参考如下代码,变量更改后会自动更新到相应的persistentstorage,退出应用后也会取最新的值

class NewsColumn {
  title: string = '';
  id: number = 0;
  constructor(title: string, id: number) {
    this.title = title;
    this.id = id;
  }
}

let columnList: NewsColumn[] = [
  new NewsColumn("推荐", 0),
  new NewsColumn("要闻", 2331),
  new NewsColumn("时政", 2257),
  new NewsColumn("党建", 2258),
  new NewsColumn("人事", 2177),
  new NewsColumn("时评", 2259),
  new NewsColumn("视频", 2586),
  new NewsColumn("服务", 1020),
  new NewsColumn("文化", 3119),
]
PersistentStorage.persistProp("newsColumn",columnList);


PersistentStorage.persistProp('testNum', 20);

@Entry
@Component
struct Storage {
  @State message: string = 'Hello World';
  @StorageLink('testNum') testNum: number = 10;

  @StorageLink('newsColumn') columnList:NewsColumn[] = []

  aboutToAppear(): void {
    console.log('newsColumn ' + JSON.stringify(this.columnList));
  }
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)

        ForEach(this.columnList, (item: NewsColumn, index: number) => {
          Column() {
            Text(item.title)
              .fontSize('15vp')
              .opacity(0.8)
              .fontWeight(400)
              .fontColor(Color.Black)
          }.onClick(() => {
          })
        })

        Text(`${this.testNum}`)
          .onClick(() => {
            // 应用退出时会保存当前结果。重新启动后,会显示上一次的保存结果
            this.testNum += 1;
            this.columnList.splice(1,0,new NewsColumn('文化' + this.testNum,1))
          })
      }
    }
    .height('100%')
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进