鸿蒙学习-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
相关推荐
2501_9197490335 分钟前
华为鸿蒙管理密码APP—小羊密码
华为·harmonyos·鸿蒙
ITUnicorn4 小时前
【HarmonyOS】时间管理类APP:做成“自适应“
harmonyos
笔触狂放4 小时前
第2章 ArkTS(上)
华为·harmonyos·鸿蒙
新元代码5 小时前
探秘鸿蒙南向开发:Hi3861 架构、编译与实战全解析
华为·架构·harmonyos
笔触狂放5 小时前
第1章 初识鸿蒙
华为·harmonyos
小雨青年6 小时前
【HarmonyOS 7 沉浸光感深度实战】 06 复杂背景下的自动反色与可读性处理
华为·harmonyos
水深火乐7 小时前
HmarkX(码笺)的本地数据库模块重构实战
harmonyos
大锅盖17 小时前
Map 搜索没有返回可信候选时,派单页面该怎么继续工作
华为·harmonyos
HarmonyOS_SDK7 小时前
HarmonyOS SDK API诊断 Skill,一键定位功能故障问题
harmonyos
大锅盖18 小时前
Canvas 签名板里的 antialias 开关,怎样确保它真正触发重绘
华为·harmonyos