鸿蒙学习-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
相关推荐
特立独行的猫a38 分钟前
开源OpenHarmony润开鸿HH-SCDAYU800A开发板开箱体验
开源·harmonyos·openharmony·hh-scdayu800a
祥睿夫子3 小时前
鸿蒙 ArkTS 函数全解析:从基础定义到高级应用,新手也能轻松掌握
harmonyos
江拥羡橙5 小时前
【目录-多选】鸿蒙HarmonyOS开发者基础
前端·ui·华为·typescript·harmonyos
爱笑的眼睛1111 小时前
HarmonyOS Stage 模型深度解析:构建现代化、高性能应用
华为·harmonyos
安卓开发者15 小时前
鸿蒙NEXT自定义能力详解:从基础使用到高级技巧
华为·harmonyos
特立独行的猫a16 小时前
HarmonyOS 鸿蒙系统自带的 SymbolGlyph 图标组件详解
华为·harmonyos·图标·symbolglyph
2501_9197490316 小时前
鸿蒙:使用EventHub实现多模块之间的通信
华为·harmonyos
2501_919749031 天前
鸿蒙:使用Emitter进行线程间通信
华为·harmonyos
SuperHeroWu71 天前
【HarmonyOS 6】仿AI唤起屏幕边缘流光特效
华为·harmonyos·特效·鸿蒙6.0·流光·ai唤起·屏幕边缘
gcios1 天前
鸿蒙-flutter 混合开发
harmonyos