0

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!

4

1 回答 1

1

关键值编码拯救!创建一个属性名称数组,并用于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;
}
于 2012-04-23T21:03:09.853 回答