HarmonyOS NEXT 版 数据存储 : 应用数据持久化 -用户首选项
将用户首选项持久化文件的内容加载到Preferences实例,每个文件唯一对应到一个Preferences实例,系统会通过静态容器将该实例存储在内存中,直到主动从内存中移除该实例或者删除该文件。提供key-value 键值型数据处理,当持久化时通过flush()接口将内存中的数据写入持久化文件中(首先在沙箱文件),但随着数据越来越多占用内存越来越大,避免大量数据存储。获取路径方法:通过Applic
应用数据持久化
指应用将内存中的数据通过文件或数据库的形式保存到设备上。
三种典型的存储数据形态
- 用户首选项 (preferences):一般用于应用配置信息,应用使用过程将文件中数据全加载到内存,数据以文本形式保存在设备
- 键值型数据库 (Key - ValueStore):非关系型数据库,数据以键值的形式进行组织、索引和存储,其中“键”作为唯一标识符。相比于关系型数据库,更容易做到跨设备跨版本兼容。
- 关系型数据库(Relational Store):以行和列的形式存储数据,广泛用于应用中的关系型数据的处理,包括一系列的增、删、改、查等。
用户首选项
提供key-value 键值型数据处理,当持久化时通过flush()接口将内存中的数据写入持久化文件中(首先在沙箱文件),但随着数据越来越多占用内存越来越大,避免大量数据存储。
首选项的持久化文件保存在应用沙箱中:
通过context获取其路径
获取路径方法:通过ApplicationContext获取应用级别的应用文件路劲
- 全局获取上下文 (UIAbilitycontext)
private context = getContext(this) as common.UIAbilityContext;
- 在生命周期/事件中获取
let applicationContext = this.context.getApplicationContext();
- 缓存下载的文件
let cacheDir = applicationContext.cacheDir;
- 文件路径:应用内存存储默认长期保存的
let filesDir = applicationContext.filesDir;
- 临时文件路劲
let tempDir = applicationContext.tempDir;
- 想要拿到的文件路径 // 获取应用文件路径
- let filePath = tempDir + 'test.txt';
- hilog.info(DOMAIN_NUMBER, TAG, `filePath: ${filePath}`);
首选项约束:
- 不支持多场景使用
- key键为string型,要求非空且长度不超过1024个字节
- 如果Value值为string类型,请使用UTF-8编码格式,可以为空,不为空时长度不超过16 * 1024 * 1024个字节
- 内存会随着存储数据量的增大而增大,所以存储的数据量应该是轻量级的,建议存储的数据不超过一万条
首选项运作机制:
将用户首选项持久化文件的内容加载到Preferences实例,每个文件唯一对应到一个Preferences实例,系统会通过静态容器将该实例存储在内存中,直到主动从内存中移除该实例或者删除该文件。
用户首选项持久化相关功能接口:
常用:
接口 | 描述 |
getPreferencesSync(context: Context, options: Options): Preferences | 获取Preferences实例。该接口存在异步接口。 |
putSync(key: string, value: ValueType): void | 将数据写入Preferences实例,可通过flush将Preferences实例持久化。该接口存在异步接口。 |
getSync(key: string, defValue: ValueType): ValueType | 获取键对应的值,如果值为null或者非默认值类型,返回默认数据defValue。该接口存在异步接口。 |
deleteSync(key: string): void | 从Preferences实例中删除名为给定Key的存储键值对。该接口存在异步接口。 |
flush(callback: AsyncCallback<void>): void | 将当前Preferences实例的数据异步存储到用户首选项持久化文件中。 |
deletePreferences(context: Context, options: Options, callback: AsyncCallback<void>): void | 从内存中移除指定的Preferences实例。若Preferences实例有对应的持久化文件,则同时删除其持久化文件。 |
开发步骤:
1.导入@kit.ArkData模块
import { preferences } from '@kit.ArkData';
2.获取Preferences实例
//Stage 模型实例
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { window } from '@kit.ArkUI';
let dataPreferences: preferences.Preferences | null = null;
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
let options: preferences.Options = { name: 'myStore' };
dataPreferences = preferences.getPreferencesSync(this.context, options);
}
}
3.写入数据
import { util } from '@kit.ArkTS';
if (dataPreferences.hasSync('startup')) {
console.info("The key 'startup' is contained.");
} else {
console.info("The key 'startup' does not contain.");
// 此处以此键值对不存在时写入数据为例
dataPreferences.putSync('startup', 'auto');
// 当字符串有特殊字符时,需要将字符串转为Uint8Array类型再存储
let uInt8Array1 = new util.TextEncoder().encodeInto("~!@#¥%……&*()——+?");
dataPreferences.putSync('uInt8', uInt8Array1);
}
4.读取数据
let val = dataPreferences.getSync('startup', 'default');
console.info("The 'startup' value is " + val);
// 当获取的值为带有特殊字符的字符串时,需要将获取到的Uint8Array转换为字符串
let uInt8Array2 : preferences.ValueType = dataPreferences.getSync('uInt8', new Uint8Array(0));
let textDecoder = util.TextDecoder.create('utf-8');
val = textDecoder.decodeWithStream(uInt8Array2 as Uint8Array);
console.info("The 'uInt8' value is " + val);
5.删除数据
dataPreferences.deleteSync('startup');
6.数据持久化
dataPreferences.flush((err: BusinessError) => {
if (err) {
console.error(`Failed to flush. Code:${err.code}, message:${err.message}`);
return;
}
console.info('Succeeded in flushing.');
})
7.删除指定文件
preferences.deletePreferences(this.context, options, (err: BusinessError) => {
if (err) {
console.error(`Failed to delete preferences. Code:${err.code}, message:${err.message}`);
return;
}
console.info('Succeeded in deleting preferences.');
})
更多推荐
所有评论(0)