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

}
相关推荐
代码改善世界3 小时前
鸿蒙电脑能被远程控制吗?ToDesk鸿蒙双向远控能力解析
华为·电脑·harmonyos
OH_TPC9 小时前
ImageKnifePro 源码解读(四):降采样策略族——按显示尺寸改衣服,不按原尺寸硬塞
harmonyos
民办二本的神10 小时前
AI 助手升级后聊天记录又丢了(二):数据一直都在,丢的是"看见"
harmonyos
huang_xiaoen1 天前
鸿蒙手机远程控制电脑哪个好用?2026鸿蒙远控软件横测推荐
华为·harmonyos·远程工作·远程工具·远程办公
爱写Bug的浮游2 天前
初识仓颉:5 分钟看懂核心语法
harmonyos·编程语言
羽落•无痕(苏晗默)2 天前
华为数通IA——14、网络服务与应用:TCP/UDP 传输层协议与 FTP、Telnet、SSH 实践
网络·网络协议·tcp/ip·网络安全·华为·udp·信息与通信
程序猿追3 天前
鸿蒙 PC 的 Ionic 工单有两个错误,按下生成后光标该去哪儿
华为·harmonyos
KevinChaos3 天前
随手备忘录手记 04|HarmonyOS 7.0新特性实验:物品图鉴的加载逻辑
华为·harmonyos
Sirius_Ji3 天前
从硬解基座到字幕与滤镜链:ffmpeg-for-HarmonyOS v0.3.2
harmonyos
用户86194177207413 天前
uni-app 鸿蒙端提现点不动?我用 UTS 插件补上了微信"确认收款"
微信·harmonyos