Reputation: 99
I'm pretty new to iOS Programming and I'm not too used with UITableView Cells.
I need to show some object properties in a table, in a "one property per cell" way.
If the data was stored in a NSArray, things would be much easier: I would use a "dynamic cell" layout and with the help of tableView:cellForRowAtIndexPath:'s indexPath variable, I'd fill the table easily.
But how to do the same when the data is "stored" in 20 properties of an object? Should I use the "static cell" layout maybe, and have a huge switch for addressing each of the 20 rows? Is there an easy and "cleaner" way to do this?
Thanks for your help!
Upvotes: 0
Views: 796
Reputation: 385890
Key-value coding to the rescue! Make an array of the property names, and use valueForKey:
to get the property values.
@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;
}
Upvotes: 1