錯誤代碼
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [arrayofNombre objectAtIndex:section]; // 傳回 id (NSNumber),非 NSInteger
}
崩潰原因
- 陣列儲存
NSNumber 物件,直接回傳導致類型不匹配
- 若
section 超出陣列範圍會拋出 NSRangeException
修正
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section >= arrayofNombre.count) return 0; // 邊界保護
NSNumber *num = arrayofNombre[section];
return [num intValue]; // 或 integerValue / longLongValue
}
資料結構建議
- 若每 section 行數固定,用
@[@5, @3, @2] 陣列儲存 NSNumber
- 若動態計算,直接回傳
self.dataSource[section].count
- 確保
numberOfSections 回傳正確區段數
Swift 版本
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard section < arrayOfNombre.count else { return 0 }
return arrayOfNombre[section].intValue
}