鸿蒙学习-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
相关推荐
今阳2 小时前
鸿蒙开发笔记-6-装饰器之@Require装饰器,@Reusable装饰器
android·app·harmonyos
余多多_zZ2 小时前
鸿蒙初学者学习手册(HarmonyOSNext_API14)_组件截图(@ohos.arkui.componentSnapshot (组件截图) )
学习·华为·harmonyos·鸿蒙·鸿蒙系统
一个处女座的程序猿O(∩_∩)O4 小时前
鸿蒙开发技术指南:从入门到精通
华为·harmonyos
陈无左耳、6 小时前
HarmonyOS学习第4天: DevEco Studio初体验
学习·华为·harmonyos
月未央8 小时前
HarmonyOS Next 开发系列:Local 状态管理实践
harmonyos
openinstall全渠道统计21 小时前
免填邀请码工具:赋能六大核心场景,重构App增长新模型
android·ios·harmonyos
shaodong112321 小时前
鸿蒙系统-同应用跨设备数据同步(分布式功能)
分布式·华为·harmonyos
敢嗣先锋21 小时前
鸿蒙5.0实战案例:基于ImageKit对图片进行处理
移动开发·harmonyos·arkui·组件化·鸿蒙开发
陈无左耳、21 小时前
HarmonyOS学习第3天: 环境搭建开启鸿蒙开发新世界
学习·华为·harmonyos
敢嗣先锋21 小时前
鸿蒙5.0实战案例:基于ArkUI的验证码实现
移动开发·harmonyos·openharmony·arkui·鸿蒙开发