鸿蒙学习-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
相关推荐
夏文强1 小时前
HarmonyOS开发者认证练习题-判断题
华为·harmonyos
Kisang.1 小时前
【HarmonyOS】ArkTS的多线程并发(下)——线程间通信对象的传递
华为·typescript·harmonyos·鸿蒙
柒儿吖6 小时前
Qt for HarmonyOS 3D图片轮播组件开源鸿蒙开发实战
qt·3d·harmonyos
爱笑的眼睛1110 小时前
HarmonyOS分布式输入法开发:实现多设备无缝输入体验
华为·harmonyos
爱笑的眼睛1110 小时前
深入HarmonyOS打印服务:从基础到高级应用开发
华为·harmonyos
鸿蒙小白龙13 小时前
OpenHarmony内核开发实战手册:编译构建、HCK框架与性能优化
harmonyos·鸿蒙·鸿蒙系统·open harmony
穆雄雄13 小时前
Rust 程序适配 OpenHarmony 实践:以 sd 工具为例
开发语言·rust·harmonyos
╰つ栺尖篴夢ゞ17 小时前
HarmonyOS之多态样式stateStyles的使用
华为·harmonyos·statestyles·多态样式
lqj_本人1 天前
鸿蒙Cordova插件架构与OnsenUI组件适配机制深度解析
华为·架构·harmonyos
猫林老师1 天前
Flutter for HarmonyOS开发指南(六):测试、调试与质量保障体系
flutter·华为·harmonyos