鸿蒙学习-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
相关推荐
OH_TPC6 小时前
HarmonyOS APP开发---“启动秀“应用引导页App,需要用到这个库
华为·harmonyos·鸿蒙
lilian2338 小时前
Harmony os 技术实战|拼豆制图43:压缩字符矩阵上线前如何拦住错位图纸
开发语言·前端·华为·矩阵·harmonyos
贾伟康10 小时前
【中国方言题库|15】HarmonyOS ArkTS 本地状态持久化实战:让保存、删除和页面返回后的数据即时一致
harmonyos·arkts·数据持久化·appstorage·preferences
2501_9197490314 小时前
华为鸿蒙免费戒咖啡APP—小羊戒咖
华为·harmonyos·鸿蒙
2501_9197490317 小时前
华为鸿蒙免费戒烟APP—小羊戒烟
华为·harmonyos·鸿蒙
二流小码农18 小时前
鸿蒙开发:了解Context
android·ios·harmonyos
math_hongfan18 小时前
鸿蒙ArkTS手势交互:拖拽、缩放、旋转与组合手势
学习·华为·交互·harmonyos·鸿蒙
zzz海羊18 小时前
2026全平台移动办公远控助手横测:从鸿蒙到工作站,ToDesk、向日葵、TeamViewer、AnyDesk谁更适配?
人工智能·华为·agent·harmonyos·teamviewer
less_1213818 小时前
HarmonyOS WPS Open SDK:对接文档阅读路径与联调自查
华为·harmonyos·wps
lilian23318 小时前
Harmony os 技术实战|拼豆制图48:把个人页字符串路由改成可穷尽的类型协议
前端·华为·harmonyos