2017-10-17 23 views
0

每當我運行應用程序時,tableView都沒有數據,等待用戶輸入。問題是,如果numberOfSections是1,它工作得很好,但是當我將其更改爲2崩潰,因爲指數超出範圍UITableView部分索引超出範圍但它並不是真的越界

func numberOfSections(in tableView: UITableView) -> Int { 
    return 2 
} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "expenseCell") as? ExpenseCell else { return UITableViewCell() } 
    let budget = userBudget[indexPath.section][indexPath.row] 
    cell.delegate = self 
    cell.configureCell(budget: budget) 
    return cell 
} 

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { 
    return true 
} 

func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { 
    return UITableViewCellEditingStyle.none 
} 

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return userBudget[section].count // <- Crash here 
    } 

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
    return "Practice with Sections \(section)" 
} 
+1

什麼是userBudget數據arrray? – iPatel

+0

'userBudget'中只有一個數組。所以首先'userBudget'的值,並確保它有多個數組。 –

+1

更改您的numberOfSections以返回userBudget?.count ?? 0(如果userBudget是可選的)ow userBudget.count。不要硬編碼值。 –

回答

0

這是因爲你正在訪問的userBudgetindex 1而我認爲它包含僅限0 index

+0

我不明白你想說什麼。 – AndreiVataselu

0

發生此次崩潰會導致您的陣列userBudget,在嘗試訪問他的第二個位置時沒有兩個元素。

必須警惕的是userBudget對minimium兩個元素...

你應該,你必須到指定值userBudget您viewDidLoad中。

+0

但這怎麼可能?正如我所說的,var ** userBudget **是一個1維數組,並且一切正常。我現在將它設置爲2D數組,並且我只使用了1個部分,所以* userBudget [0] [indexPath.row] *與1D數組是相同的,但是,這會崩潰。由於用戶尚未輸入任何內容,因此無法將其設置爲「ViewDidLoad」。 – AndreiVataselu

0

你說你將有兩個部分到你的tableView的委託,但你有一個數組只包含一個數組。基本上,當您嘗試訪問numberOfRowsInSection函數中的userBadget [1]時,它會崩潰,因爲它不存在。

更換

func numberOfSections(in tableView: UITableView) -> Int { 
    return 2 
} 

隨着

func numberOfSections(in tableView: UITableView) -> Int { 
    return userBudget.count 
}