对于小表,而不是NSDictionary,我通常使用NSArray,因为字典不保留顺序(而且您可能不想不断地重新排序)。所以我通常有一个节数组,对于每个节条目,我至少有一个节标题和一个行数组。我的行数组有,我需要呈现给定行的信息(例如行的文本等)。
单独的 row 和 section 对象,您可以将它们实现为 NSDictionary 对象本身(有时在从 JSON 或 XML 解析数据时,这是最简单的),但我通常定义自己的 Row 和 Section对象,例如:
@interface Row : NSObject
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *subtitle;
@end
和
@interface Section : NSObject
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSMutableArray *rows;
@end
然后我的表格视图控制器有一个NSArray 用于这些部分:
@property (nonatomic, strong) NSMutableArray *sections;
我这样填充它:
self.sections = [NSMutableArray array];
Section *sectionObject;
sectionObject = [[Section alloc] initWithTitle:@"Marx Brothers" rows:nil];
[sectionObject.rows addObject:[[Row alloc] initWithTitle:@"Chico" subtitle:@"Leonard Marx"]];
[sectionObject.rows addObject:[[Row alloc] initWithTitle:@"Harpo" subtitle:@"Adolph Marx"]];
[sectionObject.rows addObject:[[Row alloc] initWithTitle:@"Groucho" subtitle:@"Julius Henry Marx"]];
[sectionObject.rows addObject:[[Row alloc] initWithTitle:@"Zeppo" subtitle:@"Herbert Manfred Marx"]];
[self.sections addObject:sectionObject];
sectionObject = [[Section alloc] initWithTitle:@"Three Stooges" rows:nil];
[sectionObject.rows addObject:[[Row alloc] initWithTitle:@"Moe" subtitle:@"Moses Harry Horwitz"]];
[sectionObject.rows addObject:[[Row alloc] initWithTitle:@"Larry" subtitle:@"Louis Feinberg"]];
[sectionObject.rows addObject:[[Row alloc] initWithTitle:@"Curly" subtitle:@"Jerome Lester \"Jerry\" Horwitz"]];
[self.sections addObject:sectionObject];
然后我有典型的UITableViewDataSource 方法:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [self.sections count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
Section *sectionObject = self.sections[section];
return [sectionObject.rows count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
Section *sectionObject = self.sections[section];
return sectionObject.title;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
Section *sectionObject = self.sections[indexPath.section];
Row *rowObject = sectionObject.rows[indexPath.row];
cell.textLabel.text = rowObject.title;
cell.detailTextLabel.text = rowObject.subtitle;
return cell;
}
对于更大的数据库数据驱动表,我可能不会将数据保存在数组中,而是使用 Core Data 或 SQLite,但想法是一样的。确保我有 Section 和 Row 类,使我的表视图控制器代码不言自明,并与数据实现的细节隔离。