views:

78

answers:

3

I made a typo when creating a UITableViewCell with this code:

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CellIdentifier";
    UITableViewCell *cell = [self.tableView
        dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        NSLog(@"Creating cell");
        cell = [[[UITableViewCell alloc] 
            initWithStyle:UITableViewStylePlain
            reuseIdentifier:CellIdentifier] autorelease];
    }
    cell.textLabel.text = @"Hello";
    return cell;
}

The typo is in using UITableViewStylePlain instead of UITableViewCellStyleDefault. The code worked fine, creating new cells. Why?

+8  A: 

This is how those variables are defined.

typedef enum {
   UITableViewCellStyleDefault,
   UITableViewCellStyleValue1,
   UITableViewCellStyleValue2,
   UITableViewCellStyleSubtitle
} UITableViewCellStyle;

typedef enum {
   UITableViewStylePlain,
   UITableViewStyleGrouped
} UITableViewStyle;

Both UITableViewCellStyleDefault and UITableViewStylePlain evaluate to 0, so they're interchangeable.

kubi
Bah, you beat me by 13 seconds! ;)
Dave DeLong
Aha! Thanks kubi.
nevan
@Dave <fistpump>
kubi
+2  A: 

Because UITableViewStylePlain is declared as:

typedef enum {
    UITableViewStylePlain, 
    UITableViewStyleGrouped
} UITableViewStyle;

And UITableViewCellStyleDefault is declared as:

typedef enum {
    UITableViewCellStyleDefault,
    UITableViewCellStyleValue1,
    UITableViewCellStyleValue2,
    UITableViewCellStyleSubtitle
} UITableViewCellStyle; 

In both cases, the value you're talking about is the first in the enum, which means they both will compile to 0. Hence, they are "interchangeable" (although you definitely should not rely on this behavior in production code).

Dave DeLong
Thanks for the advice. It seems like an easy mistake to make (and not catch) as there are no immediate consequences.
nevan
+1  A: 

Both UITableViewStylePlain and UITableViewCellStyleDefault are constants with an integer value. When you use one of those, you don't actually pass the constant to the method, but the value of the constant.

As described in the other answers, both constants have the same integer value, so initWithStyle:reuseIdentifier will receive a Style ID it can work with, and it doesn't even notice you supplied a constant that doesn't have anything to do with this method.

Douwe Maan