华为鸿蒙应用--封装数据持久化工具:首选项Preferences(鸿蒙工具)-ArkTs

本文主要是介绍华为鸿蒙应用--封装数据持久化工具:首选项Preferences(鸿蒙工具)-ArkTs,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、使用方法:

0、初始化实例:一般在EntryAbility.ts的onWindowStageCreate中初始化;(可忽略)

1、将数据写入Preferences实例

function() {let arrayNum: number[] = [1, 2, 3];let arrayStr: string[] = ["5", "2", "3"];let arrayBoo: boolean[] = [true, false, true];var fruit: Fruit;fruit = new Fruit();fruit.fruitName = "Name";fruit.fruitNum = "Num";PFUtils.put("number", 10);PFUtils.put("string", "22");PFUtils.put("boolean", true);PFUtils.put("arrayNum", arrayNum);PFUtils.put("arrayStr", arrayStr);PFUtils.put("arrayBoo", arrayBoo);PFUtils.put("fruit", fruit)  // 自定义实体this.breakpointSystem.register();this.intervalId = setInterval(this.countdown, 1000);
}

2、获取键对应的值

function() {PFUtils.get("number").then((value: number) => {Logger.error(Constants.TAG, "number:" + value)})PFUtils.get("string").then((value: string) => {Logger.error(Constants.TAG, "string:" + value)})PFUtils.get("boolean").then((value: boolean) => {Logger.error(Constants.TAG, "boolean:" + value)})PFUtils.get("arrayNum").then((value: Array<number>) => {Logger.error(Constants.TAG, "Array<number>:" + value)})PFUtils.get("arrayStr").then((value: Array<string>) => {Logger.error(Constants.TAG, "Array<string>:" + value)})PFUtils.get("arrayBoo").then((value: Array<boolean>) => {Logger.error(Constants.TAG, "Array<boolean>:" + value)})PFUtils.getEntity("fruit").then((value: Fruit) => {Logger.error(Constants.TAG, "Fruit:" + value)Logger.error(Constants.TAG, "FruitName:" + value.fruitName)Logger.error(Constants.TAG, "FruitNum:" + value.fruitNum)})
}

3、其他方法:

        1、getAll:获取含有所有键值的Object对象。

        2、has:检查Preferences实例是否包含名为给定Key的存储键值对

        3、delete:从Preferences实例中删除名为给定Key的存储键值对

        4、flush:将当前Preferences实例的数据异步存储到用户首选项的持久化文件中(put中已生效)

        5、clear:清除此Preferences实例中的所有存储

二、完整代码:
import dataPreferences from '@ohos.data.preferences';
import { Constants, Logger } from '@ohos/common';let preference: dataPreferences.Preferences;
let preferenceTemp: dataPreferences.Preferences;
let context = getContext(this);export class PFUtils {/*** Read the specified Preferences persistence file and load the data into the Preferences instance.*/static async getPreferences(context: Context) {try {preference = await dataPreferences.getPreferences(context, Constants.PREFERENCES_NAME);} catch (err) {Logger.error(Constants.TAG, `Failed to get preferences, Cause: ${err}`);}}/*** Deletes the specified Preferences persistence file from memory and removes the Preferences instance.*/static async deletePreferences() {try {await dataPreferences.deletePreferences(context, Constants.PREFERENCES_NAME);} catch (err) {Logger.error(Constants.TAG, `Failed to delete preferences, Cause: ${err}`);}preference = preferenceTemp;}/*** Save the data to the Preferences.** @param data.*/static async put(key: string, value: unknown) {if (!preference) {await this.getPreferences(getContext(this));}try {if (typeof value === "number") {await  preference.put(key, value);}if (typeof value === "string") {await  preference.put(key, value);}if (typeof value === "boolean") {await  preference.put(key, value);}if (typeof value === "object") {if (Array.isArray(value)) {await  preference.put(key, value);} else {await  preference.put(key, JSON.stringify(value));}}} catch (err) {Logger.error(Constants.TAG, `Failed to put value, Cause: ${err}`);}// Store the Preference instance in the preference persistence fileawait preference.flush();}/*** Get preference data.*/static async get(key: string) {let value: unknown;if (!preference) {await this.getPreferences(getContext(this));}try {value = await preference.get(key, undefined).then();} catch (err) {Logger.error(Constants.TAG, `Failed to get value, Cause: ${err}`);}return value;}/*** Get custom entity data.*/static async getEntity(key: string) {let value: string = '';if (!preference) {await this.getPreferences(getContext(this));}try {value = (await preference.get(key, '')).toString();} catch (err) {Logger.error(Constants.TAG, `Failed to get value, Cause: ${err}`);}return JSON.parse(value);}/*** Get an Object object that contains all key values.*/static async getAll() {let value: unknown;if (!preference) {await this.getPreferences(getContext(this));}try {value = await preference.getAll().then();} catch (err) {Logger.error(Constants.TAG, `Failed to get value, Cause: ${err}`);}return value;}/*** Check if the Preferences instance contains a stored key value pair named the given Key*/static async has(key: string) {let value: boolean = false;if (!preference) {await this.getPreferences(getContext(this));}try {value = await preference.has(key).then();} catch (err) {Logger.error(Constants.TAG, `Failed to get value, Cause: ${err}`);}return value;}/*** Delete a stored key value pair named the given Key from the Preferences instance*/static async delete(key: string) {if (!preference) {await this.getPreferences(getContext(this));}try {await preference.delete(key).then();} catch (err) {Logger.error(Constants.TAG, `Failed to get value, Cause: ${err}`);}}/*** Clear all storage in this Preferences instance*/static async clear() {if (!preference) {await this.getPreferences(getContext(this));}try {await preference.clear().then();} catch (err) {Logger.error(Constants.TAG, `Failed to get value, Cause: ${err}`);}}/***Asynchronous storage of data from the current Preferences instance to the persistent file of user preferences*/static async flush() {if (!preference) {await this.getPreferences(getContext(this));}try {await preference.flush().then();} catch (err) {Logger.error(Constants.TAG, `Failed to get value, Cause: ${err}`);}}
}

这篇关于华为鸿蒙应用--封装数据持久化工具:首选项Preferences(鸿蒙工具)-ArkTs的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/531427

相关文章

基于Python开发Windows自动更新控制工具

《基于Python开发Windows自动更新控制工具》在当今数字化时代,操作系统更新已成为计算机维护的重要组成部分,本文介绍一款基于Python和PyQt5的Windows自动更新控制工具,有需要的可... 目录设计原理与技术实现系统架构概述数学建模工具界面完整代码实现技术深度分析多层级控制理论服务层控制注

利用Python操作Word文档页码的实际应用

《利用Python操作Word文档页码的实际应用》在撰写长篇文档时,经常需要将文档分成多个节,每个节都需要单独的页码,下面:本文主要介绍利用Python操作Word文档页码的相关资料,文中通过代码... 目录需求:文档详情:要求:该程序的功能是:总结需求:一次性处理24个文档的页码。文档详情:1、每个

Java中的分布式系统开发基于 Zookeeper 与 Dubbo 的应用案例解析

《Java中的分布式系统开发基于Zookeeper与Dubbo的应用案例解析》本文将通过实际案例,带你走进基于Zookeeper与Dubbo的分布式系统开发,本文通过实例代码给大家介绍的非常详... 目录Java 中的分布式系统开发基于 Zookeeper 与 Dubbo 的应用案例一、分布式系统中的挑战二

Java 缓存框架 Caffeine 应用场景解析

《Java缓存框架Caffeine应用场景解析》文章介绍Caffeine作为高性能Java本地缓存框架,基于W-TinyLFU算法,支持异步加载、灵活过期策略、内存安全机制及统计监控,重点解析其... 目录一、Caffeine 简介1. 框架概述1.1 Caffeine的核心优势二、Caffeine 基础2

使用Node.js和PostgreSQL构建数据库应用

《使用Node.js和PostgreSQL构建数据库应用》PostgreSQL是一个功能强大的开源关系型数据库,而Node.js是构建高效网络应用的理想平台,结合这两个技术,我们可以创建出色的数据驱动... 目录初始化项目与安装依赖建立数据库连接执行CRUD操作查询数据插入数据更新数据删除数据完整示例与最佳

基于Go语言开发一个 IP 归属地查询接口工具

《基于Go语言开发一个IP归属地查询接口工具》在日常开发中,IP地址归属地查询是一个常见需求,本文将带大家使用Go语言快速开发一个IP归属地查询接口服务,有需要的小伙伴可以了解下... 目录功能目标技术栈项目结构核心代码(main.go)使用方法扩展功能总结在日常开发中,IP 地址归属地查询是一个常见需求:

使用python制作一款文件粉碎工具

《使用python制作一款文件粉碎工具》这篇文章主要为大家详细介绍了如何使用python制作一款文件粉碎工具,能够有效粉碎密码文件和机密Excel表格等,感兴趣的小伙伴可以了解一下... 文件粉碎工具:适用于粉碎密码文件和机密的escel表格等等,主要作用就是防止 别人用数据恢复大师把你刚删除的机密的文件恢

PHP应用中处理限流和API节流的最佳实践

《PHP应用中处理限流和API节流的最佳实践》限流和API节流对于确保Web应用程序的可靠性、安全性和可扩展性至关重要,本文将详细介绍PHP应用中处理限流和API节流的最佳实践,下面就来和小编一起学习... 目录限流的重要性在 php 中实施限流的最佳实践使用集中式存储进行状态管理(如 Redis)采用滑动

深入浅出Spring中的@Autowired自动注入的工作原理及实践应用

《深入浅出Spring中的@Autowired自动注入的工作原理及实践应用》在Spring框架的学习旅程中,@Autowired无疑是一个高频出现却又让初学者头疼的注解,它看似简单,却蕴含着Sprin... 目录深入浅出Spring中的@Autowired:自动注入的奥秘什么是依赖注入?@Autowired

Python实战之SEO优化自动化工具开发指南

《Python实战之SEO优化自动化工具开发指南》在数字化营销时代,搜索引擎优化(SEO)已成为网站获取流量的重要手段,本文将带您使用Python开发一套完整的SEO自动化工具,需要的可以了解下... 目录前言项目概述技术栈选择核心模块实现1. 关键词研究模块2. 网站技术seo检测模块3. 内容优化分析模