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)
  }

}
相关推荐
●VON1 小时前
鸿蒙 PC Markdown 编辑器内核:在 ArkWeb 中离线运行 CodeMirror 6
安全·华为·编辑器·harmonyos·鸿蒙
YM52e3 小时前
鸿蒙Flutter Padding内边距:EdgeInsets详解
android·学习·flutter·华为·harmonyos·鸿蒙
爱写代码的阿木4 小时前
基于鸿蒙OS开发附近社交游戏平台(二十二)-ChatPage 即时通讯 UI
游戏·华为·harmonyos
红烧大青虫5 小时前
HarmonyOS应用开发实战:小事记 - 数据迁移策略:RDB 表结构变更的版本号管理与 onUpgrade 回调
后端·华为·harmonyos·鸿蒙系统
qizayaoshuap6 小时前
# 温度转换 — HarmonyOS 双向转换器与表情符号天气描述实战
华为·harmonyos
爱写代码的阿木7 小时前
基于鸿蒙OS开发附近社交游戏平台(二十三)-拉黑系统、屏蔽与全局过滤
游戏·华为·harmonyos
echohelloworld117 小时前
HarmonyOS开发实战:笔友-main_pages.json 路由表与页面注册机制
harmonyos·鸿蒙
qizayaoshuap8 小时前
# 颜色混合器 — HarmonyOS RGB调色板与Slider组件实战
华为·harmonyos
不言鹅喻9 小时前
HarmonyOS ArkTS 实战:实现一个校园体育场馆预约应用
pytorch·华为·harmonyos
网络工程小王10 小时前
【HCIE-AI】11.模型 昇腾迁移适配-精度调试-性能调优
人工智能·学习·华为·迁移学习·昇腾