鸿蒙学习-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
相关推荐
木咺吟7 小时前
鸿蒙原生应用实战(一):从零搭建快递追踪App——项目初始化与工程架构详解
华为·harmonyos
坚果派·白晓明9 小时前
【鸿蒙PC】SDL3 移植:AtomCode Skills 4 步速通多媒体库适配
c++·华为·ai编程·harmonyos·atomcode·c/c++三方库
风满城3310 小时前
鸿蒙原生应用实战(三):设置与统计页面开发 — 数据驱动的功能模块
harmonyos
xcLeigh10 小时前
鸿蒙平台 KeePass 密码管理器适配实战:从 Windows 到 鸿蒙PC 的 Electron 迁移指南
windows·electron·web·harmonyos·加密算法·keepass
金启攻11 小时前
鸿蒙原生应用开发实战(一):从零搭建“钓点日记“——项目初始化与环境配置全指南
harmonyos
风华圆舞11 小时前
鸿蒙语音识别为什么要区分 startListening 和 stopListening
华为·语音识别·harmonyos
YM52e11 小时前
鸿蒙PC ArkTS 声明合并问题深度解析与最佳实践
学习·华为·harmonyos·鸿蒙·鸿蒙系统
互联网散修11 小时前
鸿蒙实战:网络状态监听与诊断工具
网络·华为·harmonyos·网络状态监听
祭曦念12 小时前
从零开始构建鸿蒙纪念日提醒 App:ArkTS + API 24 实战
华为·harmonyos
浮芷.13 小时前
鸿蒙HarmonyOS 6.1新特性之沉浸式光感效果实现过程中的各类问题解决-鸿蒙PC版(一)
华为·harmonyos·鸿蒙·鸿蒙系统