鸿蒙学习-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
相关推荐
keepDXRcuriosity8 分钟前
鸿蒙应用开发课设——鸿蒙青藤社
harmonyos·鸿蒙
kymjs张涛25 分钟前
零一开源|前沿技术周报 #6
前端·ios·harmonyos
Georgewu12 小时前
【HarmonyOS】鸿蒙应用开发Text控件常见错误
harmonyos
Georgewu13 小时前
【HarmonyOS】富文本编辑器RichEditor详解
harmonyos
zhanshuo20 小时前
鸿蒙应用调试与测试实战全指南:高效定位问题,性能优化必备技巧+实用代码示例
harmonyos
万少1 天前
2025中了 聊一聊程序员为什么都要做自己的产品
前端·harmonyos
幽蓝计划2 天前
HarmonyOS NEXT仓颉开发语言实战案例:动态广场
华为·harmonyos
万少2 天前
第五款 HarmonyOS 上架作品 奇趣故事匣 来了
前端·harmonyos·客户端
幽蓝计划2 天前
HarmonyOS NEXT仓颉开发语言实战案例:电影App
华为·harmonyos
HMS Core2 天前
HarmonyOS免密认证方案 助力应用登录安全升级
安全·华为·harmonyos