鸿蒙学习-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
相关推荐
马剑威(威哥爱编程)10 分钟前
HarmonyOS 应用上架审核避坑:驳回五类地图与提交前自检清单
华为·harmonyos
OH_TPC3 小时前
【鸿蒙优选三方库】@react-native-ohos/react-native-screens:原生屏幕导航管理
华为·harmonyos·鸿蒙
FrameNotWork8 小时前
HarmonyOS应用《左右相册》 智感握姿实战:让操作按钮自动“站“到你拇指够得到的地方
华为·harmonyos
hacker7078 小时前
DBeaver 鸿蒙 PC 适配全记录:在 HarmonyOS 桌面端原生重建一个通用数据库工具
数据库·华为·harmonyos
hacker70710 小时前
DBeaver Community 鸿蒙 PC 适配全记录:在 HarmonyOS PC 上运行原生数据库管理工具
数据库·华为·harmonyos
HwJack2010 小时前
用 HML + CSS + JS 三段式写鸿蒙界面
javascript·css·harmonyos
小雨青年20 小时前
【HarmonyOS 7 平行视界深度实战】06 页面路由、返回栈与多层跳转怎么处理
华为·harmonyos
2501_919749031 天前
华为鸿蒙免费刷题软件—小羊免费刷题
华为·harmonyos·鸿蒙