鸿蒙学习-preferences封装

学习记录一下,封装preferences

preferences:用户首选项为应用提供Key-Value键值型的数据处理能力,支持应用持久化轻量级数据,并对其修改和查询。

数据存储形式为键值对,键的类型为字符串型,值的存储数据类型包括数字型、字符型、布尔型以及这3种类型的数组类型。

preferences有同步和异步操作两种方式,这里只封装了同步方法,大家可以参考使用

复制代码
import preferences from '@ohos.data.preferences';
class SpUtil {
  sp: preferences.Preferences
  constructor() {
    let options: preferences.Options = { name: '自定义' };
    this.sp = preferences.getPreferencesSync(getContext(this), options)
  }

  put(key: string, value: preferences.ValueType) {
    this.sp.putSync(key, value)
    this.sp.flush()
  }

  get(key: string, defValue: preferences.ValueType) {
    return this.sp.getSync(key, defValue)
  }

  clearAll() {
    this.sp.clearSync()
    this.sp.flush()
  }
}

export default new SpUtil()

文件存储路径:/data/app/el2/100/base/包名/haps/entry/preferences/文件名

使用:

复制代码
let isFirst = SpUtil.get("isFirst", true) as boolean
相关推荐
贾伟康17 小时前
【天体运行模拟|12】HarmonyOS ArkTS 本地数据文件实战:让离线资源读取失败可见可恢复
数据恢复·harmonyos·arkts·preferences·arkdata
~远在太平洋~19 小时前
05-鸿蒙 faultlog 崩溃日志分析
华为·harmonyos
Magic-ZYJ19 小时前
HarmonyOS 文件选择与读写:DocumentViewPicker、URI、沙箱目录一次搞清
深度学习·华为·harmonyos
2501_9197490319 小时前
华为鸿蒙免费提醒APP—小羊提醒
华为·harmonyos·鸿蒙
OH_TPC19 小时前
HarmonyOS APP开发---“图迹“旅行相册App,需要用到这个库
华为·harmonyos·鸿蒙
lilian23319 小时前
HarmonyOS 7 新特性(二十四)|ModularObjectExtensionAbility 与 Taihe IPC
华为·harmonyos
tsqtsqtsq030920 小时前
鸿蒙系统应用市场更新功能详解与开发适配指南
服务器·harmonyos
Georgewu21 小时前
HarmonyOS Dev Assistant (HarmonyOS开发助手)如何打通元服务开发全流程
harmonyos
2501_919749031 天前
华为鸿蒙免费计算油耗APP—小羊油耗
华为·harmonyos·鸿蒙
less_121381 天前
HarmonyOS WPS Open SDK:OpenFileRequest 构造参数与 sendRequest 打开链路
华为·sdk·harmonyos·wps·鸿蒙开发·文档编辑