HarmonyOS 鸿蒙Next数据封装类工具
HarmonyOS 鸿蒙Next数据封装类工具
这是一个数据封装类工具,适用于5.1.0
import { preferences } from '@kit.ArkData';
const TAG = "PreferencesManager"
/**
* @Description:基于 @ohos.data.preferences (用户首选项) 数据库存储的工具类
* @author:
* @date:2025-09-03
*
*/
class PreferencesManager {
dataPreferences: preferences.Preferences | null = null
/**
* 初始化操作
* @param context
*/
async init(context: Context) {
let options: preferences.Options = { name: 'test5' }
//以同步的方式初始化
this.dataPreferences = preferences.getPreferencesSync(context, options)
}
/**
* 根据key 获取值
* @param key
* @returns
*/
getStringData(key: string): Promise<preferences.ValueType> {
let value = this.dataPreferences!!.get(key, '')
return value
}
/**
* 获取bool值
* @param key
* @returns
*/
getBoolData(key: string): Promise<preferences.ValueType> {
let value = this.dataPreferences!!.get(key, false)
return value
}
/**
* 获取Int值
* @param key
* @returns
*/
getIntData(key: string, defaultData: number): Promise<preferences.ValueType> {
let value = this.dataPreferences!!.get(key, defaultData)
return value
}
/**
* 根据key 存值
* @param key
* @param value
* @returns
*/
async putData(key: string, value: preferences.ValueType) {
//将数据写入缓存的Preferences实例中,可通过flush将Preferences实例持久化
await this.dataPreferences!!.put(key, value)
//通过flush将Preferences实例持久化
await this.dataPreferences!!.flush()
}
/**
* 根据key 删除值
* @param key
* @param value
* @returns
*/
async deleteData(key: string): Promise<void> {
await this.dataPreferences!!.delete(key)
await this.dataPreferences!!.flush()
}
/**
* 清除缓存的Preferences实例中的所有数据,可通过flush将Preferences实例持久化,使用Promise异步回调。
* @returns
*/
async clearAll(): Promise<void> {
await this.dataPreferences!!.clear()
await this.dataPreferences!!.flush()
}
}
export default new PreferencesManager()
更多关于HarmonyOS 鸿蒙Next数据封装类工具的实战教程也可以访问 https://www.itying.com/category-93-b0.html
2 回复
鸿蒙Next数据封装类工具主要基于ArkTS语言实现,通过@State、@Prop、@Link等装饰器管理组件状态数据。使用LocalStorage和AppStorage进行应用级状态共享,PersistentStorage实现持久化存储。Preferences工具类可用于轻量级键值对数据存取,支持异步操作和数据变更监听。对于复杂数据结构,可通过序列化对象方式结合分布式数据管理实现跨设备同步。这些工具均基于鸿蒙API开发,不依赖Java或C语言技术栈。
更多关于HarmonyOS 鸿蒙Next数据封装类工具的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
这是一个基于HarmonyOS Next 5.1.0版本的用户首选项数据封装工具类,整体设计合理。代码使用了@kit.ArkData的preferences模块进行轻量数据存储,采用单例模式导出实例。
主要功能包括:
- 同步初始化Preferences实例
- 支持string、boolean、number类型数据的读取
- 提供数据存储、删除和清空操作
- 每次写入操作后自动调用flush()持久化
几点优化建议:
- 类型定义可以更精确,getStringData等方法返回Promise<ValueType>但实际返回的是同步值
- 错误处理需要完善,dataPreferences可能为null时使用!!强制非空存在风险
- 初始化方法建议增加异常捕获,确保Preferences实例创建成功
这个工具类封装了用户首选项的基本操作,适合在HarmonyOS Next应用中管理简单的配置数据和用户偏好设置。

