鸿蒙学习-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
相关推荐
爱笑的眼睛1110 分钟前
深入理解ArkTS装饰器:提升HarmonyOS应用开发效率
华为·harmonyos
Damon小智5 小时前
HarmonyOS 5 开发实践:分布式任务调度与设备协同架构
分布式·架构·harmonyos
●VON9 小时前
双非大学生自学鸿蒙5.0零基础入门到项目实战 -《基础篇》
android·华为·harmonyos·鸿蒙
Damon小智19 小时前
鸿蒙分布式数据服务(DDS)原理与企业同步实战
分布式·华为·harmonyos
猫林老师1 天前
HarmonyOS自动化测试与持续集成实战指南
ci/cd·华为·harmonyos
寂然如故1 天前
拥抱未来:HarmonyOS NEXT 开发新范式深度解析
华为·harmonyos
国霄1 天前
(2)Kotlin/Js For Harmony——如何复用ViewModel
harmonyos
星释1 天前
鸿蒙Flutter三方库适配指南:08.联合插件开发
flutter·华为·harmonyos
爱笑的眼睛111 天前
HarmonyOS WaterFlow瀑布流布局深度解析:从原理到性能优化
华为·harmonyos
星释1 天前
鸿蒙Flutter三方库适配指南:06.插件适配原理
flutter·华为·harmonyos