arkTs数据存储
1、AppStorage
(不是持久化的,需要使用PersistentStorage持久化存储,目前我使用MMKV做的持久化)
AppStorage是应用全局的UI状态存储,是和应用的进程绑定的,由UI框架在应用程序启动时创建,为应用程序UI状态属性提供中央存储。
封装Util:
export class StoreUtil {
static setOrCreate<T>(propName: string, newValue: T): void {
AppStorage.setOrCreate(propName, newValue)
}
static delete(propName: string): boolean {
return AppStorage.delete(propName)
}
static clear(): boolean {
return AppStorage.clear()
}
static size(): number {
return AppStorage.size()
}
static get<T>(propName: string) {
return AppStorage.get<T>(propName)
}
/**
* 保存uiContext
*/
static setUIContext(uiContext: UIContext) {
StoreUtil.setOrCreate<UIContext>(StorageKey.uiContext, uiContext)
}
/**
* 获取uiContext
*/
static getUIContext() {
return AppStorage.get<UIContext>(StorageKey.uiContext)
}
/**
* 保存会员名字
* @param memberInfo 会员信息
*/
static saveMemberInfo(memberName: string) {
StoreUtil.setOrCreate<string>(StorageKey.MEMBER_NAME, memberName)
}
/**
* 获取会员名字
* @param memberInfo 会员信息
*/
static getMemberInfo() {
return AppStorage.get<string>(StorageKey.MEMBER_NAME)
}
}
export enum StorageKey {
//1:会员名字
MEMBER_NAME = "member_name",
}
使用:
import { StoreUtil, StorageKey } from '@ohos/datastore';
@StorageLink(StorageKey.MEMBER_NAME) menberName?: string = StoreUtil.getMemberInfo()
Text('用户名:' + (this.menberName??''))
2、Preferences(首选项)
首选项模块(Preferences)提供Key-Value键值型数据(后续简称KV数据)的处理接口,实现对轻量级KV数据的查询、修改和持久化功能。
封装Util:
// 用户首选项为应用提供Key-Value键值型的数据处理能力,支持应用持久化轻量级数据,并对其修改和查询。
// 是轻量级的本地存储解决方案,适用于存储少量简单数据,适合作为应用配置数据的存储方式。
import { common } from '@kit.AbilityKit';
import { preferences } from '@kit.ArkData';
const PREFERENCES_NAME: string = 'MyAppStore';
export class PreferenceManager {
private preferences?: preferences.Preferences;
private context = getContext(this) as common.UIAbilityContext;
private static instance: PreferenceManager;
private constructor() {
this.initPreference(PREFERENCES_NAME);
}
// 初始化 获取Preferences实例
async initPreference(storeName: string): Promise<void> {
return preferences.getPreferences(this.context, storeName)
.then((preferences: preferences.Preferences) => {
this.preferences = preferences;
});
}
// 获取PreferenceManager实力
public static getInstance(): PreferenceManager {
if (!PreferenceManager.instance) {
PreferenceManager.instance = new PreferenceManager();
}
return PreferenceManager.instance;
}
// 存储
async setValue<T>(key: string, value: T): Promise<void> {
if (this.preferences) {
this.preferences.put(key, JSON.stringify(value)).then(() => {
this.saveUserData();
})
} else {
this.initPreference(PREFERENCES_NAME).then(() => {
this.setValue<T>(key, value);
});
}
}
// 获取
async getValue<T>(key: string): Promise<T | null> {
if (this.preferences) {
return this.preferences.get(key, '').then((res: preferences.ValueType) => {
let value: T | null = null;
if (res) {
value = JSON.parse(res as string) as T;
}
return value;
});
} else {
return this.initPreference(PREFERENCES_NAME).then(() => {
return this.getValue<T>(key);
});
}
}
// 检验是否有存储
async hasValue(key: string): Promise<boolean> {
if (this.preferences) {
return this.preferences.has(key);
} else {
return this.initPreference(PREFERENCES_NAME).then(() => {
return this.hasValue(key);
});
}
}
// 删除
async deleteValue(key: string): Promise<void> {
if (this.preferences) {
this.preferences.delete(key).then(() => {
this.saveUserData();
});
} else {
this.initPreference(PREFERENCES_NAME).then(() => {
this.deleteValue(key);
});
}
}
// 将缓存的Preferences实例中的数据异步存储到用户首选项的持久化文件中
saveUserData() {
this.preferences?.flush();
}
}
使用:
import { PreferenceManager } from '@ohos/datastore';
private preferenceManager: PreferenceManager = PreferenceManager.getInstance();
async aboutToAppear() {
this.isLoge = await this.preferenceManager.getValue<boolean>('isLoge')??false
}
3、MMKV(可持久化存储)
三方库链接:OpenHarmony三方库中心仓
ohpm install @tencent/mmkv
封装Util:
import { MMKV } from '@tencent/mmkv';
import { common } from '@kit.AbilityKit';
export class DataCacheUtils {
private mmkv: MMKV | null = null
private isEmpty(obj: object | string) {
return obj === null || obj === undefined || obj === ''
}
protected save(key: string, value: string) {
try {
if (this.mmkv == null) {
MMKV.initialize(getContext(this) as common.ApplicationContext)
this.mmkv = MMKV.defaultMMKV()
}
if (!this.isEmpty(value)) {
this.mmkv.encodeString(key, value)
} else {
this.mmkv.removeValueForKey(key)
}
} catch (error) {
}
}
protected get(key: string): string {
try {
if (this.mmkv == null) {
MMKV.initialize(getContext(this) as common.ApplicationContext)
this.mmkv = MMKV.defaultMMKV()
}
if (!this.isEmpty(key)) {
return this.mmkv?.decodeString(key)??''
}
} catch (error) {
return ""
}
return ""
}
}
export class DataMMKVManage extends DataCacheUtils {
private static instance: DataMMKVManage;
// 获取PreferenceManager实力
public static getInstance(): DataMMKVManage {
if (!DataMMKVManage.instance) {
DataMMKVManage.instance = new DataMMKVManage();
}
return DataMMKVManage.instance;
}
/**
* 保存全局session
* @param value
*/
public saveUserSession(value: string) {
this.save('session', value)
}
/**
* 获取全局session
* @param value
*/
public getUserSession() {
return this.get('session')
}
}
使用:
import { DataMMKVManage } from '@ohos/datastore';
private dataMMKVManage: DataMMKVManage = DataMMKVManage.getInstance();
this.session = this.dataMMKVManage.getUserSession()
this.dataMMKVManage.saveUserSession('124345')