鸿蒙开发之用户首选项、本地存储、持久化存储封装
鸿蒙本地存储、数据持久化
·
代码封装 记得单独调用
import {preferences} from "@kit.ArkData"
import { common } from "@kit.AbilityKit";
import { BusinessError } from "@kit.BasicServicesKit";
type ValueType = number | string | boolean | Array<number> | Array<string> | Array<boolean> | Uint8Array | object | bigint
export class PreferenceStore{
static preferenceStore:preferences.Preferences|null=null
/**
* 初始化用户首选项
* @param context
*/
static initPreferences(context:common.UIAbilityContext){
let options:preferences.Options={name:'myStore'}
PreferenceStore.preferenceStore=preferences.getPreferencesSync(context,options)
console.log('初始化了存储')
}
/**
* 设置本地存储并做持久化
* @param name
* @param value
*/
static set(name:string,value:ValueType){
PreferenceStore.preferenceStore?.putSync(name,value)
console.log('做了存储')
//做本地存储持久化
PreferenceStore.preferenceStore?.flush((err: BusinessError) => {
if (err) {
console.error(`Failed to flush. Code:${err.code}, message:${err.message}`);
return;
}
console.info('成功持久化.');
})
}
/**
* 读取本地存储
* @param name
* @returns
*/
static get(name:string){
return PreferenceStore.preferenceStore?.getSync(name,"")
}
/**
* 删除本地存储
* @param name
*/
static remove(name:string){
PreferenceStore.preferenceStore?.deleteSync(name)
}
/**
* 更多请参阅文档
*/
}
EntryAbility.ets文件里做初始化
onWindowStageCreate(windowStage: window.WindowStage): void {
// Main window is created, set main page for this ability
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
windowStage.loadContent('pages/preferences/index', (err) => {
if (err.code) {
hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return;
}
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.');
});
//初始化用户首选项,记得先导入!!!!!!!!!
PreferenceStore.initPreferences(this.context)
}
更多推荐


所有评论(0)