鸿蒙Next ArkTS存储数据的工具类实现方法

在鸿蒙Next中使用ArkTS开发时,如何高效实现一个存储数据的工具类?希望能提供具体的实现方法,包括本地存储、数据加密和性能优化等方面的建议。

2 回复

鸿蒙Next ArkTS存储数据?简单!用Preferences工具类,三步搞定:

  1. 创建实例:
let prefs = await preferences.getPreferences(context, 'myData');
  1. 存数据:
await prefs.put('key', 'value');
  1. 取数据:
let value = await prefs.get('key', 'default');

记得加await,不然数据就“离家出走”了!持久化存储so easy~

更多关于鸿蒙Next ArkTS存储数据的工具类实现方法的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在鸿蒙Next(HarmonyOS NEXT)中,使用ArkTS实现数据存储的工具类,主要通过@ohos.data.preferences(轻量级偏好数据库)或@ohos.data.relationalStore(关系型数据库)实现。以下是基于Preferences的轻量级键值对存储工具类示例:

import preferences from '@ohos.data.preferences';
import { BusinessError } from '@ohos.base';

export class StorageUtil {
  private static instance: StorageUtil | null = null;
  private preferences: preferences.Preferences | null = null;

  // 单例模式
  public static getInstance(): StorageUtil {
    if (!StorageUtil.instance) {
      StorageUtil.instance = new StorageUtil();
    }
    return StorageUtil.instance;
  }

  // 初始化Preferences(异步)
  async init(context: Context, name: string): Promise<void> {
    try {
      this.preferences = await preferences.getPreferences(context, name);
      console.info('StorageUtil: Preferences initialized');
    } catch (err) {
      const error = err as BusinessError;
      console.error(`StorageUtil: Initialization failed, code: ${error.code}, message: ${error.message}`);
    }
  }

  // 存储字符串
  async putString(key: string, value: string): Promise<void> {
    if (!this.preferences) {
      console.error('StorageUtil: Preferences not initialized');
      return;
    }
    try {
      await this.preferences.put(key, value);
      await this.preferences.flush();
    } catch (err) {
      const error = err as BusinessError;
      console.error(`StorageUtil: Put string failed, code: ${error.code}, message: ${error.message}`);
    }
  }

  // 读取字符串
  async getString(key: string, defaultValue: string = ''): Promise<string> {
    if (!this.preferences) {
      console.error('StorageUtil: Preferences not initialized');
      return defaultValue;
    }
    try {
      return await this.preferences.get(key, defaultValue);
    } catch (err) {
      const error = err as BusinessError;
      console.error(`StorageUtil: Get string failed, code: ${error.code}, message: ${error.message}`);
      return defaultValue;
    }
  }

  // 删除数据
  async delete(key: string): Promise<void> {
    if (!this.preferences) {
      console.error('StorageUtil: Preferences not initialized');
      return;
    }
    try {
      await this.preferences.delete(key);
      await this.preferences.flush();
    } catch (err) {
      const error = err as BusinessError;
      console.error(`StorageUtil: Delete failed, code: ${error.code}, message: ${error.message}`);
    }
  }

  // 清空所有数据
  async clear(): Promise<void> {
    if (!this.preferences) {
      console.error('StorageUtil: Preferences not initialized');
      return;
    }
    try {
      await this.preferences.clear();
      await this.preferences.flush();
    } catch (err) {
      const error = err as BusinessError;
      console.error(`StorageUtil: Clear failed, code: ${error.code}, message: ${error.message}`);
    }
  }
}

使用示例:

// 在EntryAbility中初始化
import { UIAbility } from '@kit.AbilityKit';
import { StorageUtil } from '../utils/StorageUtil';

export default class EntryAbility extends UIAbility {
  async onCreate(): Promise<void> {
    const storage = StorageUtil.getInstance();
    await storage.init(this.context, 'myAppStorage');
  }
}

// 在页面中使用
const storage = StorageUtil.getInstance();
await storage.putString('username', '张三');
const name = await storage.getString('username');

关键说明:

  1. 单例模式:确保全局唯一实例。
  2. 异步操作:所有存储方法均为异步,需使用await
  3. 错误处理:捕获BusinessError并输出日志。
  4. 数据持久化flush()方法确保数据写入磁盘。
  5. 适用场景:适合配置信息、用户偏好等轻量数据。

对于复杂数据结构,建议使用relationalStore(关系型数据库)或序列化为JSON字符串存储。

回到顶部