キーバリューコーディングが救いの手を差し伸べます!プロパティ名の配列を作成し、を使用valueForKey:
してプロパティ値を取得します。
@implementation MyTableViewController {
// The table view displays the properties of _theObject.
NSObject *_theObject;
// _propertyNames is the array of properties of _theObject that the table view shows.
// I initialize it lazily.
NSArray *_propertyNames;
}
- (NSArray *)propertyNames {
if (!propertyNames) {
propertyNames = [NSArray arrayWithObjects:
@"firstName", @"lastName", @"phoneNumber", /* etc. */, nil];
}
return propertyNames;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self propertyNames].count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
}
NSArray *propertyNames = [self _propertyNames];
NSString *key = [propertyNames objectAtIndex:indexPath.row];
cell.textLabel.text = [[_theObject valueForKey:key] description];
return cell;
}