****加上數據分離
#import "HMViewController.h" #import "HMStudent.h"@interface HMViewController () <UITableViewDataSource> @property (weak, nonatomic) IBOutlet UITableView *tableView;/** 數據列表 */ @property (nonatomic, strong) NSArray *dataList; @end@implementation HMViewController- (NSArray *)dataList {if (_dataList == nil) {HMStudent *stu1 = [[HMStudent alloc] init];stu1.title = @"黑馬1期";stu1.desc = @"牛叉";// 生成編號數組NSMutableArray *arrayM1 = [NSMutableArray array];for (int i = 0; i < 10; i++) {[arrayM1 addObject:[NSString stringWithFormat:@"%@ - %04d", stu1.title, i]];}stu1.students = arrayM1;HMStudent *stu2 = [[HMStudent alloc] init];stu2.title = @"黑馬2期";stu2.desc = @"也牛叉";// 生成編號數組NSMutableArray *arrayM2 = [NSMutableArray array];for (int i = 0; i < 20; i++) {[arrayM2 addObject:[NSString stringWithFormat:@"%@ - %04d", stu2.title, i]];}stu2.students = arrayM2;_dataList = @[stu2, stu1];}return _dataList; }#pragma mark - 數據源方法 // 如果沒有實現,默認是1 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {return self.dataList.count; }// 每個分組中的數據總數 // sction:分組的編號 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {// students數組中的元素數量// 取出數組中對應的學員信息 // HMStudent *stu = self.dataList[section]; // return stu.students.count;// 計算數量的代碼,由于層次比較深,建議使用上面的代碼return [[self.dataList[section] students] count]; }// 告訴表格控件,每一行cell單元格的細節 // indexPath // @property(nonatomic,readonly) NSInteger section; 分組 // @property(nonatomic,readonly) NSInteger row; 行 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {// 實例化TableViewCell時,使用initWithStyle方法來進行實例化UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];// 取出indexPath對應的數據HMStudent *stu = self.dataList[indexPath.section];cell.textLabel.text = stu.students[indexPath.row];return cell; }// 返回分組的標題文字 - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { // HMStudent *stu = self.dataList[section]; // return stu.title;return [self.dataList[section] title]; }- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section { // HMStudent *stu = self.dataList[section]; // return stu.desc;// 直接從數組中取出的對象是id類型,因為沒有明確的類型,因此不能使用.語法,只能使用getter方法return [self.dataList[section] desc]; }@end
?