HarmonyOS 通过用户首选项实现数据持久化

HarmonyOS 通过用户首选项实现数据持久化

1. 介绍

text 复制代码
用户首选项提供 Key-Value键值型的数据处理能力,支持修改和查询。Preferences会把数据存储到内存中,通过调用 flush 接口将数据持久化。Preferences会随着存放的数据量越多而导致应用占用的内存越大,因此,Preferences不适合存放过多的数据,也不支持通过配置加密,适用的场景一般为应用保存用户的个性化设置(字体大小,是否开启夜间模式)等。

2.限制

  • 首选项无法保证进程并发安全,会有文件损坏和数据丢失的风险,不支持在多进程场景下使用。
  • Key键为string类型,要求非空且长度不超过1024个字节。
  • 如果Value值为string类型,请使用UTF-8编码格式,可以为空,不为空时长度不超过16 * 1024 * 1024个字节。
  • 内存会随着存储数据量的增大而增大,所以存储的数据量应该是轻量级的,建议存储的数据不超过一万条,否则会在内存方面产生较大的开销。

3.api

参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-data-preferences-V5

4.使用示例(使用单例模式封装Preferences)

ts 复制代码
import { Context } from '@ohos.arkui.UIContext';
import preferences from '@ohos.data.preferences';
import { BusinessError } from '@kit.BasicServicesKit';

export class PreferencesData{
  private static  _instance:PreferencesData;
  private _data:preferences.Preferences|null=null;
  private constructor() {
  }
  // 获取 当前实例
  public static get Instance():PreferencesData
  {
    return PreferencesData._instance || (PreferencesData._instance=new PreferencesData());
  }

  // 初始化 Preferences 对象
  // 使用时首先要初始化 Preferences 对象
  public init(context:Context,name:string="myStore"){
    if(this._data) return;
     this._data=preferences.getPreferencesSync(context,{name})
  }


  public get data():preferences.Preferences|null{
    return this._data;
  }

  // 存储
  public set(key:string,value:preferences.ValueType):void
  {
    this.data?.putSync(key,value)
  }
  // 取值
  public get(key:string):preferences.ValueType|undefined
  {
     return this.data?.getSync(key,"default");
  }
  // 删除
  public del(key:string):void
  {
    this.data?.deleteSync(key);
  }
  // 做持久化
  public flush():void
  {
    this.data?.flush((err:BusinessError)=>{
      if(err){
        console.log("错误的存储内容,"+err.message)
      }else{
        console.log("持久化存储成功")
      }
    })
  }
  // 监听
  public on(callback:(key:string)=>void):void
  {
    this.data?.on("change",callback)
  }
  // 删除存储
  public removeStore(context:Context,name:string="myStore",callback:(err:BusinessError)=>void=(err)=>{}):void
  {
    preferences.deletePreferences(context,name)
  }

}
相关推荐
一只栖枝5 小时前
华为 HCIE 大数据认证中 Linux 命令行的运用及价值
大数据·linux·运维·华为·华为认证·hcie·it
zhanshuo9 小时前
在鸿蒙里优雅地处理网络错误:从 Demo 到实战案例
harmonyos
zhanshuo9 小时前
在鸿蒙中实现深色/浅色模式切换:从原理到可运行 Demo
harmonyos
whysqwhw14 小时前
鸿蒙分布式投屏
harmonyos
whysqwhw15 小时前
鸿蒙AVSession Kit
harmonyos
whysqwhw17 小时前
鸿蒙各种生命周期
harmonyos
whysqwhw18 小时前
鸿蒙音频编码
harmonyos
whysqwhw18 小时前
鸿蒙音频解码
harmonyos
whysqwhw18 小时前
鸿蒙视频解码
harmonyos
whysqwhw18 小时前
鸿蒙视频编码
harmonyos