鸿蒙学习-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
相关推荐
程序员黑豆1 小时前
鸿蒙应用开发实战:从零学会自定义组件
前端·华为·harmonyos
FrameNotWork3 小时前
HarmonyOS 6.0 LocalStorage页面级存储
华为·交互·harmonyos
FF2501_940228584 小时前
Grid 构建月历网格:7 列模板 + 日期占位算法
后端·华为·harmonyos·鸿蒙系统
FrameNotWork4 小时前
HarmonyOS 6.0 自定义指令与手势组合:从单指到多指的交互进阶
华为·交互·harmonyos
胡琦博客4 小时前
HarmonyOS 智能工具箱(二):OCR 文字识别工具
华为·ocr·harmonyos
FrameNotWork4 小时前
HarmonyOS 6.0 数据可视化图表
华为·信息可视化·harmonyos
程序员黑豆4 小时前
鸿蒙应用开发:6种图片加载方式详解
前端·华为·harmonyos
qizayaoshuap5 小时前
# ❌ 井字棋 — 鸿蒙ArkTS Minimax AI算法与博弈系统设计
人工智能·算法·华为·harmonyos
●VON5 小时前
鸿蒙 PC Markdown 编辑器界面语言切换:跟随系统、简体中文与 English 的完整状态闭环
华为·编辑器·harmonyos·鸿蒙
Catrice05 小时前
HarmonyOS ArkTS 实战:实现一个校园就业信息与校招应用
华为·harmonyos