HarmonyOS:根据用户首选项Preferences生成的工具类

import dataPreferences from '@ohos.data.preferences';
import common from '@ohos.app.ability.common';
import preferences from '@ohos.data.preferences';

const PREFERENCE_NAME = "MyPreStore"
export class SpUtil {
  private static instance: SpUtil
  private context = getContext(this) as common.UIAbilityContext
  private preferences?: preferences.Preferences

  constructor() {
    this.initPreference(PREFERENCE_NAME)
  }

  public static getInstance(): SpUtil {
    if (!SpUtil.instance) {
      SpUtil.instance = new SpUtil()
    }
    return SpUtil.instance
  }

  async initPreference(storeName: string): Promise<void> {
    return dataPreferences.getPreferences(this.context, storeName)
      .then((preferences: preferences.Preferences) => {
        this.preferences = preferences
      })
  }

  /**
   * 异步存储,数据存储在内存和应用沙盒中
   * 如果key对应的value 已经存在,将更新value
   */
  async setValue<T>(key: string, value?: T): Promise<void> {
    if (this.preferences) {
      this.preferences.put(key, JSON.stringify(value)).then(() => {
        this.saveToFile()
      })
    } else {
      //初始化并存储数据
      this.initPreference(PREFERENCE_NAME).then(() => {
        this.setValue<T>(key, value)
      })
    }
  }

  /**
   * 根据key值获取对应的value ,未查找到对应的value,使用def
   * @param key
   * @param def 默认值
   */
  async getValue<T>(key: string): Promise<T | null> {
    if (this.preferences) {
      return this.preferences.get(key, "").then((valueType: preferences.ValueType) => {
        let data: T | null = null
        if (valueType) {
          data = JSON.parse(valueType as string) as T
        }
        return data
      })
    } else {
      return this.initPreference(PREFERENCE_NAME).then(() => {
        return this.getValue<T>(key)
      })
    }
  }

  /**
   * 校验对应的key是否有对应的value
   */
  async hasValue(key: string): Promise<boolean> {
    if (this.preferences) {
      return this.preferences.has(key)
    } else {
      return this.initPreference(PREFERENCE_NAME).then(() => {
        return this.hasValue(key)
      })
    }
  }

  /**
   * 删除key 对应的value,同时会删除App沙盒中的数据
   */
  async deleteValue(key: string): Promise<void> {
    if (this.preferences) {
      this.preferences.delete(key).then(() => {
        this.saveToFile()
      })
    } else {
      this.initPreference(PREFERENCE_NAME).then(() => {
        this.deleteValue(key)
      })
    }
  }

  /**
   * 将数据持久化到本地文件中(应用沙盒)
   */
  saveToFile() {
    this.preferences?.flush()
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值