Swift自定义TableView中Timestamp数组无法显示且崩溃问题排查
Hey there, let's sort out that crash you're facing! The Thread 1: Fatal error: Index out of range error here means you're trying to access a position in datesArray that doesn't exist—and this almost always happens because your TableView is asking for more rows than your array actually contains. Here's how to fix it step by step:
1. Make sure your TableView's row count matches the array length
The most common culprit is the numberOfRowsInSection method returning a number that doesn't match datesArray.count. For example, if you hardcode a number like 5 or accidentally return the count of your amount array (which might be longer/shorter), this crash will happen.
Update your method to return the actual count of the dates array:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return AddSubtractMoneyController.datesArray.count }
Pro tip: If your amount array and dates array are supposed to be paired one-to-one, add a check somewhere to ensure their counts are equal—otherwise you'll end up with mismatched data even if you avoid the crash.
2. Add safety checks in cellForRowAt
Even if you fix the row count, it's good practice to add a guard clause to prevent accidental out-of-range access, especially if your array might be modified asynchronously. Here's how to adjust your cell setup code:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "YourCustomCellID", for: indexPath) as! YourCustomCell // Guard against invalid index guard indexPath.row < AddSubtractMoneyController.datesArray.count else { cell.dateLbl.text = "" cell.amountLbl.text = "" return cell } // Safe access to the arrays cell.dateLbl.text = AddSubtractMoneyController.datesArray[indexPath.row] if indexPath.row < yourAmountArray.count { cell.amountLbl.text = yourAmountArray[indexPath.row] } else { cell.amountLbl.text = "" } return cell }
3. Verify your array population logic
Double-check where you're adding data to your arrays. If you only add an amount to the amount array but forget to add a corresponding date to datesArray (or vice versa), their counts will diverge, leading to this crash when the TableView tries to access a missing element. Always make sure you add data to both arrays in pairs when a new transaction is recorded.
4. Avoid static array references if possible
Using a static array like AddSubtractMoneyController.datesArray can lead to unexpected issues if the array is modified from another thread or part of the app without the TableView knowing. Consider moving the arrays to the ViewController that manages the TableView, or using a dedicated data source object to keep data consistent and easier to track.
内容的提问来源于stack exchange,提问作者Coding while Loading

