如何将Double类型数组存入UserDefaults并在TableView持久化加载
Got it, let's get your transaction data sticking around between app launches! The issue here is that you're not persisting your moneySpentArray to UserDefaults correctly—luckily, this is a straightforward fix. Here's exactly how to implement it:
1. Define a Reusable Key (Avoid Typos!)
First, create a constant for your UserDefaults key somewhere accessible (like at the top of your ViewController). This prevents accidental typos when saving/loading:
private let moneySpentArrayKey = "SavedMoneySpentTransactions"
2. Load the Array When the App Starts
In your viewDidLoad() (or wherever you initialize your array), pull the saved data from UserDefaults. We'll use a default empty array to handle the first launch case where no data exists yet:
override func viewDidLoad() { super.viewDidLoad() // Load saved array, default to empty if no data exists moneySpentArray = UserDefaults.standard.array(forKey: moneySpentArrayKey) as? [Double] ?? [] // Don't forget to reload your TableView here to show the saved data tableView.reloadData() }
3. Save the Array After Updating It
When your addToMoney function updates the array (after the user taps Submit), immediately save the updated array to UserDefaults. Add this to your IBAction or directly in addToMoney:
@IBAction func submitButtonTapped(_ sender: UIButton) { // Get the user's input (add validation here to avoid invalid numbers!) guard let inputText = amountTextField.text, let newAmount = Double(inputText), newAmount > 0 else { // Show an error alert if input is invalid let alert = UIAlertController(title: "Invalid Amount", message: "Please enter a valid positive number.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default)) present(alert, animated: true) return } // Update your array addToMoney(amount: newAmount) // Save the updated array to UserDefaults UserDefaults.standard.set(moneySpentArray, forKey: moneySpentArrayKey) // Explicit synchronize is optional in modern iOS, but it's safe to include for older versions UserDefaults.standard.synchronize() // Refresh the TableView to show the new entry tableView.reloadData() // Clear the text field for next input amountTextField.text = "" } func addToMoney(amount: Double) { moneySpentArray.append(amount) // Add any other logic you need here (like formatting, sorting, etc.) }
Quick Notes to Avoid Headaches
- Validation: Always validate user input before adding it to your array—this prevents
nilvalues or negative amounts from breaking your data. - UserDefaults Limits: Keep in mind that UserDefaults is meant for small amounts of data (like user preferences or short transaction lists). If you plan to store hundreds/thousands of transactions later, you might want to switch to Core Data or a local database like Realm.
- Type Safety: The
as? [Double] ?? []cast ensures you get a valid Double array even if the saved data is corrupted or missing.
内容的提问来源于stack exchange,提问作者Coding while Loading

