HarmonyOS系统应用持久化技术工具包及封装组件
文章目录
一、preferences:首选项
preferences()首选项通常用于保存应用的配置信息key-Value格式。如:保存用户的个性化设置(字体大小,是否开启夜间模式)等
***preferences中的value中的类型支持:数字型、字符型、布尔型及3中类型的数组
通过文本的形式保存在设备中,应用使用过程中会将文本中的数据全量加载到内存中,所以访问速度快、效率高,
但不适合需要存储大量数据的场景。
应用首选项的持久化文件保存至物理文件,需要到虚拟机沙箱才有,外部看不到
使用方法:
1.导包: import preferences from '@ohos.data.preferences'
2.创建实例: getPreferences(context: Context, name: string): Promise<Preferences>
例: this.store = preferences.getPreferences(getContext(this),'自定配置的名字userStore') // 异步的 返回值为:Promise<Preferences>
3.获取数据: get(key: string, defValue: ValueType): Promise<ValueType>
例: const res = await this.store.get(key,'') // 当没有数据时,默认''
await this.store.flush()
4.修改数据: put(key: string, value: ValueType): Promise<void>
例: await this.store.put(key,value) //支持 数字型number、字符型string、布尔型boolean及3中类型的数组
await this.store.flush()
5.删除数据: delete(key: string): Promise<void>
await this.store.delete(key)
await this.store.flush()
6.当每个业务执行完成记得: .flush() // 刷新(防止文件挂起)
首选项工具包
import preferences from '@ohos.data.preferences';
// 工具
export class ConfigStore {
private fileName:string = 'myConfig'
// 构造器方法
constructor(fileName?:string) {
if(fileName){
this.fileName = fileName
}
}
//首选项实例
private getStore() {
let store= preferences.getPreferences( getContext(this), this.fileName )
return preferences.getPreferences( getContext(this), this.fileName )
}
//设置
async setData(key:string, data:string){
const store = await this.getStore()
await store.put(key, data)
await store.flush()
}
//检索
async getData(key:string){
const store = await this.getStore()
const data = await store.get(key, '') //统一默认类型,没有就是空字符串
await store.flush()
return JSON.stringify(data) //始终统一返回字符串格式,哪怕是一个对象描述
}
//删除
async delData(key:string){
const store = await this.getStore()
await store.delete(key)
await store.flush()
}
}
首选项工具包(单例模式:懒汉式)
import preferences from '@ohos.data.preferences';
// 工具
/**
* 使用单例模式 // 减少资源的占用
* 1.将构造进行私有(私有)
* 2.创建静态私有实例(私有)
* 3.封装公用使用对象(公用) ==初始化实例校验
*/
export default class PreferencesHelper {
// 1.将构造进行私有(私有)
private static pre: PreferencesHelper
// 2.创建静态私有实例(私有)
private constructor(fileName?: string) {
if (fileName) {
this.fileName = fileName
}
}
// 3.封装公用使用对象(公用)==初始化实例校验
public static getInstance(): PreferencesHelper {
// public 不加默认共用
// 懒汉模式
// 饿汉模式是在私有上直接实例,但是不用则会占用资源
if (!PreferencesHelper.pre) {
PreferencesHelper.pre = new PreferencesHelper()
}
return PreferencesHelper.pre
}
// 下面使用必须要基于单例模式===封装信息
private readonly fileName: string = 'myConfig'
private getStore():Promise<preferences.Preferences>{
return preferences.getPreferences(getContext(this), this.fileName)
}
//设置
async putData(key: string, data: string):Promise<void> {
try {
const store = await this.getStore()
await store.put(key, data)
await store.flush()
}catch (err){
throw new Error(err)
}
}
//检索
async getData(key: string