/*
* 数据持久化
* */
class PreferencesUtil{
prefMap: Map<string, preferences.Preferences> = new Map()
async loadPreference(context, name: string){
try {
// 加载preferences
let pref = await preferences.getPreferences(context, name)
this.prefMap.set(name, pref)
console.log('testTag', `加载Preferences[${name}]成功`)
} catch (e) {
console.log('testTag', `加载Preferences[${name}]失败`, JSON.stringify(e))
}
}
async putPreferenceValue(name: string, key: string, value: preferences.ValueType){
if (!this.prefMap.has(name)) {
console.log('testTag', `Preferences[${name}]尚未初始化!`)
return
}
try {
let pref = this.prefMap.get(name)
// 写入数据
await pref.put(key, value)
// 刷盘
await pref.flush()
console.log('testTag', `保存Preferences[${name}.${key} = ${value}]成功`)
} catch (e) {
console.log('testTag', `保存Preferences[${name}.${key} = ${value}]失败`, JSON.stringify(e))
}
}
async getPreferenceValue(name: string, key: string, defaultValue: preferences.ValueType){
if (!this.prefMap.has(name)) {
console.log('testTag', `Preferences[${name}]尚未初始化!`)
return
}
try {
let pref = this.prefMap.get(name)
// 读数据
let value = await pref.get(key, defaultValue)
console.log('testTag', `读取Preferences[${name}.${key} = ${value}]成功`)
return value
} catch (e) {
console.log('testTag', `读取Preferences[${name}.${key} ]失败`, JSON.stringify(e))
}
}
}
const preferencesUtil = new PreferencesUtil()
export default preferencesUtil as PreferencesUtil
import preferencesUtil from '../Common/utils'
方法引用
await preferencesUtil.loadPreference(this.context, "club")
let firstInstall: string = await preferencesUtil.getPreferenceValue("club","firstInstall","0") as string
注意如果每次读取的都是默认值看一下是否设置了运行时保留App数据,见下图
截屏2024-06-12 15.47.48.png
截屏2024-06-07 14.34.01.png