鸿蒙开发-用户首选项他来了

204 阅读2分钟

用户首选项-数据持久化

基本概念

什么是数据持久化?

将内存数据保存到磁盘或者数据库的过程,我们称为数据持久化

持久化的作用:

可以保证数据永久留存,直到我们主动删除为止

用户首选项:

用户首选项支持持久化轻量级数据,并提供相关方法对其新增、修改、查询、删除

用户首选项运行机制:

image.png

注意事项

  • Key键为string类型,要求非空且长度不超过80个字节。
  • 如果Value值为string类型,可以为空,不为空时长度不超过8192个字节,大约为8K大小
  • 内存会随着存储数据量的增大而增大,所以存储的数据量应该是轻量级的,建议存储的数据不超过一万条,否则会在内存方面产生较大的开销。

用户首选项-添加数据

import { preferences } from '@kit.ArkData'

@Entry
@Component
struct Pre_test {
  build() {
    Column() {
      Button('用户首选项新增和修改数据')
        .onClick(async () => {
          // 1. 获取用户首选项 创建一个名为 test 的文件
          let pre = preferences.getPreferencesSync(getContext(), { name: 'test' })
          // 2. 添加数据
          pre.putSync('rhj', 'hello world') // 写入内存
          // 3. 提交数据到磁盘
          await pre.flush() // 写入磁盘
        })
    }
    .width('100%')
    .height('100%')
  }
}

image.png

用户首选项-修改数据

修改和添加一样,key 不变,改变value即可修改

image.png

image.png

用户首选项-获取数据

import { preferences } from '@kit.ArkData'

@Entry
@Component
struct Pre_test {
  build() {
    Column() {
      Button('用户首选项新增和修改数据')
        .onClick(async () => {
          // 1. 获取用户首选项 创建一个名为 test 的文件
          let pre = preferences.getPreferencesSync(getContext(), { name: 'test' })
          // 2. 添加数据
          pre.putSync('rhj', ['hello world rhj', 'hello world rhj2']) // 写入内存
          // 3. 提交数据到磁盘
          await pre.flush() // 写入磁盘
        })
      Button('用户首选项读取数据')
        .onClick(async () => {
          // 1. 获取用户首选项 获取文件指向
          let pre = preferences.getPreferencesSync(getContext(), { name: 'test' })
          // 2. 读取数据
          let value = pre.getSync('rhj', '')
          // 3. 输出数据
          AlertDialog.show({ message: JSON.stringify(value, null, 2) })
        })
    }
    .width('100%')
    .height('100%')
  }
}

image.png

用户首选项-删除数据

import { preferences } from '@kit.ArkData'

@Entry
@Component
struct Pre_test {
  build() {
    Column() {
      Button('用户首选项新增和修改数据')
        .onClick(async () => {
          // 1. 获取用户首选项 创建一个名为 test 的文件
          let pre = preferences.getPreferencesSync(getContext(), { name: 'test' })
          // 2. 添加数据
          pre.putSync('rhj', ['hello world rhj', 'hello world rhj2']) // 写入内存
          // 3. 提交数据到磁盘
          await pre.flush() // 写入磁盘
        })
      Button('用户首选项读取数据')
        .onClick(async () => {
          // 1. 获取用户首选项 获取文件指向
          let pre = preferences.getPreferencesSync(getContext(), { name: 'test' })
          // 2. 读取数据
          let value = pre.getSync('rhj', '')
          // 3. 输出数据
          AlertDialog.show({ message: JSON.stringify(value, null, 2) })
        })

      Button('用户首选项删除数据')
        .onClick(async () => {
          // 1. 获取用户首选项 获取文件指向
          let pre = preferences.getPreferencesSync(getContext(), { name: 'test' })
          // 2. 删除数据
          pre.deleteSync('rhj')
          // 3. 提交数据到磁盘
          await pre.flush()
        })

    }
    .width('100%')
    .height('100%')
  }
}

image.png