HarmonyOS应用开发实战:猫猫大作战-preferences 偏好存储

发布时间:2026/7/29 13:31:23
HarmonyOS应用开发实战:猫猫大作战-preferences 偏好存储 前言Preferences是 HarmonyOS 的轻量级键值对存储适合保存用户偏好设置和少量数据。在「猫猫大作战」中Preferences 存储音效开关、最高分、提醒时间等配置。一、Preferences 基础import { preferences } from kit.ArkData; async function savePreferences(context: Context): Promisevoid { const store await preferences.getPreferences(context, game_prefs); await store.put(highScore, 5000); await store.put(soundEnabled, true); await store.put(playerName, 小明); await store.put(reminderHour, 20); await store.flush(); // 写入磁盘 } async function loadPreferences(context: Context): Promisevoid { const store await preferences.getPreferences(context, game_prefs); const highScore store.get(highScore, 0) as number; const soundOn store.get(soundEnabled, true) as boolean; const name store.get(playerName, 玩家) as string; }二、Preferences 操作方法说明示例put(key, value)写入put(score, 100)get(key, def)读取get(score, 0)delete(key)删除delete(oldKey)flush()持久化必须调用才写入磁盘clear()清空全部谨慎使用三、游戏中的应用class SettingsManager { private store: preferences.Preferences | null null; async init(context: Context): Promisevoid { this.store await preferences.getPreferences(context, game_prefs); } async getHighScore(): Promisenumber { return this.store?.get(highScore, 0) as number ?? 0; } async setHighScore(score: number): Promisevoid { await this.store?.put(highScore, score); await this.store?.flush(); } async getSoundEnabled(): Promiseboolean { return this.store?.get(soundEnabled, true) as boolean ?? true; } async setSoundEnabled(enabled: boolean): Promisevoid { await this.store?.put(soundEnabled, enabled); await this.store?.flush(); } }四、Preferences vs AppStorage特性PreferencesAppStorage持久化✅ 磁盘❌ 内存适用场景设置、高分运行时共享操作方式异步 get/put同步 get/setUI 绑定❌ 手动✅ StorageLink提示最佳实践是 AppStorage 运行时读写、Preferences 持久化应用退出时从 AppStorage 同步到 Preferences。五、最佳实践存储少量数据适合 100 条键值对调用 flush写入后必须 flush 落盘提供默认值get(key, default)避免空值应用启动时加载aboutToAppear从 Preferences 恢复到 AppStorage总结Preferences 是轻量级持久化键值存储适合游戏设置和最高分。核心要点getPreferences打开存储、put/get读写、flush()持久化、 提供默认值。如果这篇文章对你有帮助欢迎点赞、收藏⭐、关注你的支持是我持续创作的动力相关资源Preferences 官方文档第 133 篇reset第 135 篇rdb第 140 篇AppStorage