鸿蒙学习-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
相关推荐
SuperHeroWu713 小时前
【HarmonyOS】元服务入门详解 (一)
华为·harmonyos·鸿蒙·元服务·卡片·免安装
Georgewu13 小时前
【HarmonyOS】ArkUI-X 跨平台框架入门详解(一)
harmonyos
SuperHeroWu713 小时前
【HarmonyOS】元服务概念详解
华为·harmonyos·鸿蒙·概念·元服务·详解
Georgewu14 小时前
【HarmonyOS】ArkUI-X一套代码跑多端的跨平台方案概念详解
harmonyos
zhanshuo18 小时前
HarmonyOS NEXT 智能场景识别实战:让设备主动思考的关键技术揭秘
harmonyos
zhanshuo1 天前
HarmonyOS分布式能力全解析:手机一放下,音箱自动响起!
harmonyos
zhanshuo1 天前
基于HarmonyOS的智能灯光控制系统设计:从定时触发到动作联动全流程实战
harmonyos
weixin_541299941 天前
鸿蒙应用开发: 鸿蒙项目中使用私有 npm 插件的完整流程
华为·npm·harmonyos·鸿蒙
Georgewu1 天前
【HarmonyOS】元服务概念详解
harmonyos
Georgewu1 天前
【HarmonyOS】元服务入门详解 (一)
harmonyos