import preferences from '@ohos.data.preferences';
class PreferencesUtil {
prefMap: Map<string, preferences.Preferences> = new Map()
async loadPreference(context, name: string) {
try { //加载preferences
const pref = await preferences.getPreferences(context, name)
this.prefMap.set(name, pref)
console.log('testTag', `加载Preference[${name}]成功`)
} catch (e) {
console.log('testTag', `加载Preference[${name}]失败`, JSON.stringify(e))
}
}
async putPreferenceValue(name: string, key: string, value: preferences.ValueType) {
if (!this.prefMap.has(name)) {
console.log('testTag', `Preference[${name}]尚未初始化!`)
return
}
try {
const pref = this.prefMap.get(name)
//写入数据
await pref.put(key, value)
//刷盘
await pref.flush()
console.log('testTag', `保存Preference[${name}.${key} = ${value}]成功!`)
} catch (e) {
console.log('testTag', `保存Preference[${name}.${key} = ${value}]失败!`, JSON.stringify(e))
}
}
async getPreferenceValue(name: string, key: string, defaultValue: preferences.ValueType) {
if (!this.prefMap.has(name)) {
console.log('testTag', `Preference[${name}]尚未初始化!`)
return
}
try {
const pref = this.prefMap.get(name)
//读取数据
const value = await pref.get(key, defaultValue)
console.log('testTag', `读取Preference[${name}.${key} = ${value}]成功!`)
return value
} catch (e) {
console.log('testTag', `读取Preference[${name}.${key}]失败`, JSON.stringify(e))
}
}
}
HarmonyOS4开发 数据持久化-用户首选项 封装
最新推荐文章于 2024-11-11 19:29:13 发布