首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS UITableView numberOfRowsInSection:陣列元素需轉換為 NSInteger

     編輯:程式設計綜合問答

錯誤代碼

- (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
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved