鸿蒙学习-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
相关推荐
lmy_loveF4 小时前
构建第一个HarmonyOS元服务
华为·harmonyos
哦***74 小时前
鸿蒙小知识 | 华为耳机双击没法暂停音乐?
华为·音频·harmonyos
木木子2217 小时前
# 鸿蒙 ArkTS 实战:秒表 Stopwatch(示例 5)
数据结构·华为·list·harmonyos
zdj_develop18 小时前
鸿蒙应用开发实战(一):应用程序包概述
华为·harmonyos
智塑未来19 小时前
鸿蒙更智能:从“人找App”到“意图即服务”
华为·harmonyos
qizayaoshuap1 天前
鸿蒙 ArkTS 实战:数据存储 Preferences 本地持久化(示例 95)
华为·harmonyos
木木子221 天前
HarmonyOS NEXT 折叠面板与Step组件实战开发
华为·harmonyos
程序员黑豆1 天前
鸿蒙应用开发:AppStorage 全局状态存储用法教程
前端·harmonyos
梦想不只是梦与想1 天前
鸿蒙性能优化:启动速度
性能优化·harmonyos·启动速度