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

}
相关推荐
万少1 小时前
2025中了 聊一聊程序员为什么都要做自己的产品
前端·harmonyos
网络小白不怕黑2 小时前
华为设备 QoS 流分类与流标记深度解析及实验脚本
网络·华为
网络小白不怕黑2 小时前
华为交换机堆叠与集群技术深度解析附带脚本
网络·华为
幽蓝计划14 小时前
HarmonyOS NEXT仓颉开发语言实战案例:动态广场
华为·harmonyos
万少20 小时前
第五款 HarmonyOS 上架作品 奇趣故事匣 来了
前端·harmonyos·客户端
幽蓝计划20 小时前
HarmonyOS NEXT仓颉开发语言实战案例:电影App
华为·harmonyos
HMS Core1 天前
HarmonyOS免密认证方案 助力应用登录安全升级
安全·华为·harmonyos
生如夏花℡1 天前
HarmonyOS学习记录3
学习·ubuntu·harmonyos
伍哥的传说1 天前
鸿蒙系统(HarmonyOS)应用开发之手势锁屏密码锁(PatternLock)
前端·华为·前端框架·harmonyos·鸿蒙
funnycoffee1231 天前
Huawei 6730 Switch software upgrade example版本升级
java·前端·华为