新手求助:如何在应用重启时加载上一次运行的coins数据?
Hey there! Since you're new to this, let's break down how to keep track of the user's coins even after the app restarts—this is called data persistence, and it's a super common need for apps that save user progress.
Core Idea
The key is to save the latest coin count to a local persistent storage every time it changes, then load that value when the app starts up. If there's no saved value (like on first install), you'll set the initial coin amount you want to give users.
Platform-Specific Implementations
Below are examples for the most common app development platforms:
1. Android (Kotlin/Java)
Use SharedPreferences—Android's built-in lightweight storage for small key-value data:
- Load saved coins on app launch:
// Put this in your main activity's onCreate method val sharedPref = getSharedPreferences("GameStorage", Context.MODE_PRIVATE) // The second parameter is the default value (initial coins for first-time users) var userCoins = sharedPref.getInt("user_coins", 100)
- Save coins whenever the value changes:
fun updateAndSaveCoins(newCoinCount: Int) { userCoins = newCoinCount val editor = sharedPref.edit() editor.putInt("user_coins", userCoins) editor.apply() // Async save, won't block the main thread }
2. iOS (Swift)
Use UserDefaults—iOS's equivalent lightweight storage:
- Load saved coins on app launch:
// Put this in your AppDelegate or SceneDelegate launch method let defaults = UserDefaults.standard // Check if a saved value exists; if not, use the initial 100 coins var userCoins = defaults.integer(forKey: "user_coins") == 0 ? 100 : defaults.integer(forKey: "user_coins")
- Save coins on value change:
func updateAndSaveCoins(_ newCoinCount: Int) { userCoins = newCoinCount UserDefaults.standard.set(userCoins, forKey: "user_coins") }
3. Cross-Platform (Flutter)
Use the shared_preferences plugin (add it to your pubspec.yaml first):
- Load saved coins on app initialization:
import 'package:shared_preferences/shared_preferences.dart'; // In your initState or a startup async function final prefs = await SharedPreferences.getInstance(); int userCoins = prefs.getInt('user_coins') ?? 100; // Default to 100 if no save exists
- Save coins on value change:
Future<void> updateAndSaveCoins(int newCoinCount) async { userCoins = newCoinCount final prefs = await SharedPreferences.getInstance(); await prefs.setInt('user_coins', userCoins); }
Important Notes
- Save immediately on change: Don't wait until the app closes to save—if the app crashes unexpectedly, you'll lose the latest coin count.
- Validate values: Add checks to make sure coins don't go negative (if that's a rule for your game) before saving.
- Scale if needed: If you end up needing to save more complex data (like levels, items, etc.), you can move to a local database like SQLite or Realm, but lightweight storage is perfect for just tracking coins.
内容的提问来源于stack exchange,提问作者Stucked so I came here

