(本篇笔记对应课程第 30 节)
P30《29.数据持久化-用户首选项》
实现数据持久化在harmonyOS中有很多种方式,比较常见的是以下两种:


读取项目持久化文件,这是一个IO操作,比较耗时,因此是一个异步操作,返回一个Promise对象:

将 routerInfo 类定义到 viewmodel 目录下的一个文件中:


改造首页,增加一个设置字体大小的功能:



实现用户持久化:
1、在 util 目录下定义一个 PreferenceUtil.ts 的首选项工具类文件:

2、定义加载 Preference 方法:
异步写法:

同步写法:

语句后输入 .if 可快速将前面的语句包裹在 if() 中:

3、定义写入 Preference 方法:

4、定义读取 Preference 方法:

5、在 Ability 的 onCreate 钩子函数中加载 Preference:

6、在首页中使用 获取 Preference 方法:
7、字号改变时写入 Preference :

测试:
测试 Preference 必须用模拟器
启动模拟器:

点击 返回 按钮,应用关闭,Ability被销毁:

再次打开应用,发现数据持久化效果成功了!

实践:
