我想在自定义表格视图中显示一系列日期,其中包含您花费的金额以及您花费此金额的日期。我创建了两个不同的数组,一个用于支付金额,另一个用于节省花费时间的数组。
我的代码上没有任何编译错误,但是当我运行应用程序时,它崩溃并且在cell.dateLbl.text = AddSubtractMoneyController.datesArray[indexPath.row]
行,并且给了我这个错误:
线程1:致命错误:索引超出范围
为什么会发生这种情况的任何想法?
class SpendingHistoryViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let userDefaults = UserDefaults.standard
@IBOutlet weak var tableViewSpending: UITableView!
@IBOutlet weak var youSpentLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.tableViewSpending.delegate = self
self.tableViewSpending.dataSource = self
//GETS user defaults that was set in ADDSUBTRACTMONEY VC - and then sets the default to Array- then gets total
let moneySpentArray = UserDefaults.standard.array(forKey: "moneySpent") as? [Double] ?? [Double]()
let arraySum = moneySpentArray.reduce(0.0, +)
AddSubtractMoneyController.moneySpentArray = moneySpentArray
youSpentLabel.text = String(format: "%.2f", arraySum)
let spendingDateArray = UserDefaults.standard.array(forKey: "spendingDateArray") as? [String] ?? [String]()
AddSubtractMoneyController.datesArray = spendingDateArray
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return(AddSubtractMoneyController.moneySpentArray.count)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 75
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableViewSpending.dequeueReusableCell(withIdentifier: "cell") as! SpendingHistoryTableViewCell
cell.spentAmountLbl.text = String(format: "%.2f", AddSubtractMoneyController.moneySpentArray[indexPath.row])
cell.dateLbl.text = AddSubtractMoneyController.datesArray[indexPath.row]
return cell
}
class AddSubtractMoneyController: NSObject {
let userDefaults = UserDefaults.standard
static var moneySpentArray:Array<Double> = []
static var savingsArray: Array <Double> = []
static var daysArray: Array <Int> = []
static var datesArray: Array <String> = []
//let savingsArraySaved = "savingsArraySaved"
class func addToMoneySpentArray( amountISpent: Double) {
moneySpentArray.append(amountISpent)
UserDefaults.standard.set(moneySpentArray, forKey: "moneySpent")
}
class func addToSavingsArray( finalDailySavedAmount: Double) {
savingsArray.append(finalDailySavedAmount)
UserDefaults.standard.set(savingsArray, forKey: "savingsTotalArray")
//print(savingsArray)
}
class func addDayInSavingsArray(dayCount: Int){
daysArray.append(dayCount)
UserDefaults.standard.set(daysArray, forKey: "dayCountArray")
}
class func addDateToMoneySpentArray(date: String) {
datesArray.append(date)
UserDefaults.standard.set(datesArray, forKey: "spendingDateArray")
print(datesArray)
}