鸿蒙学习-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
相关推荐
youtootech11 小时前
HarmonyOS 实战教程(八):个人中心与华为云服务集成 —— 以「柚兔自测量表」为例
华为·华为云·harmonyos
红烧大青虫11 小时前
HarmonyOS应用《玄象》开发实战:掷钱动画:animateTo + 缓动曲线的物理感模拟
harmonyos·鸿蒙
二流小码农13 小时前
鸿蒙开发:实现文本渐变效果
android·ios·harmonyos
程序员黑豆14 小时前
鸿蒙应用开发:Refresh + List 下拉刷新组件使用教程
前端·华为·harmonyos
fengxinzi_zack14 小时前
HarmonyOS应用《玄象》开发实战:MansionListPage 列表页:List / ListItem / LazyForEach 性能优化
harmonyos·鸿蒙
youtootech15 小时前
HarmonyOS 实战教程(九):响应式布局与断点系统 —— 以「柚兔自测量表」为例
华为·harmonyos
山璞15 小时前
将一个 Flutter 项目转为用 ArkUI-X 框架实现(4)
flutter·harmonyos
2501_9197490315 小时前
华为鸿蒙隐私文件加密APP—小羊加密室
华为·harmonyos
程序员黑豆16 小时前
鸿蒙开发实战:使用 List 组件构建新闻列表
前端·华为·harmonyos
爱写代码的阿森16 小时前
鸿蒙三方库 | harmony-utils之RegexUtil正则匹配验证详解
服务器·华为·harmonyos·鸿蒙·huawei