鸿蒙学习-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
相关推荐
鸿蒙开发5 小时前
共享 Schema 与 SchemaFactory
前端·后端·harmonyos
二流小码农7 小时前
HarmonyOS开发助手,0代码让元服务从开发到上架
android·ios·harmonyos
贾伟康9 小时前
【共创稿事节】第一张服务卡片:2×2 今日菜谱的克制设计
microsoft·harmonyos·arkts·鸿蒙
2501_944525769 小时前
开源鸿蒙平台 KMP_CMP 三方库「Atrium」适配全流程
microsoft·开源·harmonyos
less_121389 小时前
鸿蒙 WPS Open SDK 二开复盘:从注册、打开到回传的完整能力链
服务器·sdk·harmonyos·wps·鸿蒙开发
2601_9495758610 小时前
开源鸿蒙平台 CMP 三方库「voyager」适配全流程
华为·开源·harmonyos
2601_9495758611 小时前
开源鸿蒙平台 CMP 三方库「compose-multiplatform-2048」适配全流程
华为·开源·harmonyos
网络豆14 小时前
开源鸿蒙平台 CMP 三方库「kmp-compose-tab-container」适配全流程
华为·开源·harmonyos
2601_9495758614 小时前
开源鸿蒙平台 KMP_CMP 三方库「PreCompose」适配全流程
华为·开源·harmonyos
resh_people15 小时前
开源鸿蒙平台 CMP 三方库「LazySurface」适配全流程
华为·开源·harmonyos