import dataPreferences from '@ohos.data.preferences';
import common from '@ohos.app.ability.common';
import preferences from '@ohos.data.preferences';
const PREFERENCE_NAME = "MyPreStore"
export class SpUtil {
private static instance: SpUtil
private context = getContext(this) as common.UIAbilityContext
private preferences?: preferences.Preferences
constructor() {
this.initPreference(PREFERENCE_NAME)
}
public static getInstance(): SpUtil {
if (!SpUtil.instance) {
SpUtil.instance = new SpUtil()
}
return SpUtil.instance
}
async initPreference(storeName: string): Promise<void> {
return dataPreferences.getPreferences(this.context, storeName)
.then((preferences: preferences.Preferences) => {
this.preferences = preferences
})
}
/**
* 异步存储,数据存储在内存和应用沙盒中
* 如果key对应的value 已经存在,将更新value
*/
async setValue<T>(key: string, value?: T): Promise<void> {
if (this.preferences) {
this.preferences.put(key, JSON.stringify(value)).then(() => {
this.saveToFile()
})
} else {
//初始化并存储数据
this.initPreference(PREFERENCE_NAME).then(() => {
this.setValue<T>(key, value)
})
}
}
/**
* 根据key值获取对应的value ,未查找到对应的value,使用def
* @param key
* @param def 默认值
*/
async getValue<T>(key: string): Promise<T | null> {
if (this.preferences) {
return this.preferences.get(key, "").then((valueType: preferences.ValueType) => {
let data: T | null = null
if (valueType) {
data = JSON.parse(valueType as string) as T
}
return data
})
} else {
return this.initPreference(PREFERENCE_NAME).then(() => {
return this.getValue<T>(key)
})
}
}
/**
* 校验对应的key是否有对应的value
*/
async hasValue(key: string): Promise<boolean> {
if (this.preferences) {
return this.preferences.has(key)
} else {
return this.initPreference(PREFERENCE_NAME).then(() => {
return this.hasValue(key)
})
}
}
/**
* 删除key 对应的value,同时会删除App沙盒中的数据
*/
async deleteValue(key: string): Promise<void> {
if (this.preferences) {
this.preferences.delete(key).then(() => {
this.saveToFile()
})
} else {
this.initPreference(PREFERENCE_NAME).then(() => {
this.deleteValue(key)
})
}
}
/**
* 将数据持久化到本地文件中(应用沙盒)
*/
saveToFile() {
this.preferences?.flush()
}
}