HarmonyOS ohos.data.preferences 数据存储,使用preferences 单例模式

HarmonyOS ohos.data.preferences 数据存储,使用preferences 单例模式。

HarmonyOS
2024-11-22 09:33:25
1095浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
Excelsior_abit

可以写一个GlobalContext类,在EntryAbility的时候初始化preferences ,并存入进去,然后使用的时候,取出来使用即可。

export class GlobalContext { 
  private constructor() { 
  } 
 
  private static instance: GlobalContext; 
  private _objects = new Map<string, Object>(); 
 
  public static getContext(): GlobalContext { 
    if (!GlobalContext.instance) { 
      GlobalContext.instance = new GlobalContext(); 
    } 
    return GlobalContext.instance; 
  } 
 
  getObject(value: string): Object | undefined { 
    return this._objects.get(value); 
  } 
 
  setObject(key: string, objectClass: Object): void { 
    this._objects.set(key, objectClass); 
  } 
} 
 
EntryAbility: 
let productPreferences: Function = (() => { 
  let preferences: Promise<dataPreferences.Preferences> = dataPreferences.getPreferences(context, key); 
  return preferences; 
}); 
GlobalContext.getContext().setObject('getProductPreferences', preferences); 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
分享
微博
QQ
微信
回复
2024-11-22 15:50:42


相关问题
HarmonyOS @ohos.data.preferences
1318浏览 • 1回复 待解决
HarmonyOS @ohos.data.preferences 数据处理
1172浏览 • 1回复 待解决
实现模式下的数据存储
2111浏览 • 1回复 待解决
HarmonyOS 使用preferences存储的限制
1038浏览 • 1回复 待解决
HarmonyOS preferences无法持久化存储
973浏览 • 1回复 待解决
HarmonyOS preferences.putSync 存储报错
1085浏览 • 1回复 待解决
HarmonyOS data_preferences remove不起作用
949浏览 • 1回复 待解决
HarmonyOS Preferences如何实现持久性存储
1133浏览 • 1回复 待解决
HarmonyOS 模式不生效
976浏览 • 1回复 待解决
HarmonyOS navigation有模式
921浏览 • 1回复 待解决