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

}
相关推荐
YM52e11 小时前
分页查询的基石:ArkTS 为鸿蒙商品列表设计 LIMIT/OFFSET 的表
android·学习·华为·harmonyos
math_hongfan11 小时前
主从嵌套层次分明:ArkUI 订单卡片内嵌明细的鸿蒙界面
学习·华为·harmonyos
woshihuanglaoshi14 小时前
事务加持防超卖:ArkTS 在鸿蒙里玩转 TRANSACTION 出入库
学习·华为·harmonyos
世人万千丶14 小时前
去重插入与超限淘汰:ArkTS 实现鸿蒙搜索历史的 LIMIT 艺术
运维·服务器·学习·华为·harmonyos·鸿蒙
贾伟康15 小时前
【知律|08】HarmonyOS ArkTS 语音阅读实战:管理法条朗读状态和中断恢复
生命周期·harmonyos·arkts·语音合成·arkui
woshihuanglaoshi16 小时前
十二商品二十流水:鸿蒙进销存种子数据装满预警看板
学习·华为·harmonyos
2501_9197490318 小时前
华为鸿蒙背书背课文APP—小羊背诵
华为·harmonyos·鸿蒙
YM52e18 小时前
六十条商品铺满三页:鸿蒙分页列表种子数据与加载效果
华为·harmonyos
todoitbo20 小时前
把蓝耘接入鸿蒙健康教练:一句话打卡,模型估热量,网关记账
华为·ai·harmonyos·蓝耘·第三方api
2501_9197490321 小时前
华为鸿蒙复盘统计记账APP—小羊统计
华为·harmonyos·鸿蒙