Why does this TableView code work?
I made a typo when creating a UITableViewCell
with this code:
- (UITableViewCell *)tableView:(UITableView *)tableView开发者_StackOverflow中文版
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?
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.
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).
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.
精彩评论