2010-05-03 110 views
1

在使用以下代碼創建UITableViewCell時我犯了錯字:爲什麼這個TableView代碼有效?

- (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; 
} 

錯字是使用UITableViewStylePlain而不是UITableViewCellStyleDefault。代碼工作正常,創建新單元格。爲什麼?

回答

10

這是如何定義這些變量。

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

typedef enum { 
    UITableViewStylePlain, 
    UITableViewStyleGrouped 
} UITableViewStyle; 

兩個UITableViewCellStyleDefaultUITableViewStylePlain評估爲0,所以他們互換。

+0

Bah,你打我13秒! ;) – 2010-05-03 17:12:22

+0

啊哈!謝謝kubi。 – 2010-05-03 17:19:53

+0

@Dave kubi 2010-05-03 18:15:05

3

因爲UITableViewStylePlain聲明爲:

typedef enum { 
    UITableViewStylePlain, 
    UITableViewStyleGrouped 
} UITableViewStyle; 

而且UITableViewCellStyleDefault聲明爲:

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

在這兩種情況下,你在談論的價值是在enum第一,這意味着他們都將編譯爲0。因此,它們是「可互換的」(儘管在生產代碼中您肯定應該依賴此行爲而不是)。

+0

感謝您的建議。由於沒有直接的後果,這似乎是一個容易犯的錯誤(而不是捕捉)。 – 2010-05-03 17:33:47

1

UITableViewStylePlainUITableViewCellStyleDefault是具有整數值的常量。當你使用其中的一個時,你實際上並沒有將該常量傳遞給該方法,而是將該常量值傳遞給該方法。

正如其他答案中所述,兩個常量具有相同的整數值,所以initWithStyle:reuseIdentifier將收到一個它可以使用的樣式ID,它甚至不會注意到您提供了一個沒有任何東西的常量用這種方法。