鸿蒙学习-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
相关推荐
GitCode官方11 小时前
开源鸿蒙跨平台直播|QRN 跨端鸿蒙一体化实战
人工智能·华为·开源·harmonyos·atomgit
ZZZMMM.zip11 小时前
演示架构师-PPT大纲生成的HarmonyOS开发实践
人工智能·华为·powerpoint·harmonyos·鸿蒙·鸿蒙系统
国服第二切图仔12 小时前
HarmonyOS APP《画伴梦工厂》开发第60篇-分布式软总线2.0——多设备协同新范式
分布式·wpf·harmonyos
2501_9185823712 小时前
50 Canvas 动画:@State + @Watch + animateTo 驱动模式
华为·harmonyos·鸿蒙系统
xianjixiance_12 小时前
43 短距通信场景汇总:NFC / 二维码 / 剪贴板 / 超级终端
华为·harmonyos·鸿蒙系统
木木子2213 小时前
[特殊字符] 音乐播放器——状态驱动的多媒体控制
android·开发语言·华为·php·harmonyos
拥抱太阳061613 小时前
HarmonyOS 应用开发《掌上英语》第2篇:ArkTS 模块化开发:Index.ets 统一导出模式深度解析
pytorch·ubuntu·harmonyos
不羁的木木13 小时前
《HarmonyOS技术精讲-Core Vision Kit》第4篇:人脸检测与关键点定位
华为·harmonyos
拥抱太阳061614 小时前
HarmonyOS 应用开发《掌上英语》第3篇:响应式架构:BreakpointModel 与多设备适配方案
华为·架构·harmonyos
w1395485642215 小时前
双色叠加雷达图:DuetReport 双人对比
华为·harmonyos·鸿蒙系统