小さなテーブルの場合、 ではなくNSDictionary
を使用するのが一般的NSArray
です。これは、辞書は順序を保持しないためです (そして、おそらく継続的に並べ替えを行いたくないでしょう)。そのため、通常はセクションの配列があり、各セクション エントリには、少なくともセクション タイトルと行の配列があります。行の配列には、特定の行を表示するために必要な情報 (行のテキストなど) があります。
個々の行オブジェクトとセクション オブジェクトは、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;
}
より大きなデータベース データ ドリブン テーブルの場合、データを配列に保持せずにコア データまたは SQLite を使用する場合がありますが、考え方は同じです。テーブル ビュー コントローラーのコードを一目瞭然にし、データ実装の詳細から隔離するクラスがあることSection
を確認してください。Row