2011-12-08 58 views
0

我想用類似的枚舉類型定義:選擇由IF-THEN-ELSE條件語句

if (foo>0){ 
typedef enum { 
    Form_FirstName = 0, 
    Form_NamePrefix, 
    Form_LastName, 
    Form_Email, 
    Form_Phone 
} Form; 
} else { 
    typedef enum { 
    Form_FirstName = 0, 
    Form_LastName, 
    Form_Phone 
} Form; 
} 

可以這樣做?我應該在哪裏做這件事?在.m中還是在.h中?我想用這個UITableView。

+0

編譯器說什麼? – onnoweb

回答

3

首先,枚舉是編譯類型結構。

其次,你有一個範圍界定問題。因爲您正在定義ifelse範圍內的枚舉類型。它不會在if..else..聲明之外具有可視性。

您需要找到一種不同的方式來區分基於狀態的索引。

更新基於OP的後續的問題:

OK,你需要地圖的某種。例如,你可以這樣做:

定義你的枚舉。

enum { 
    Form_FirstName = 0, 
    Form_NamePrefix, 
    Form_LastName, 
    Form_Email, 
    Form_Phone 
}; 

假設你的類有一個indexes伊娃與通常@property@synthesize,請設置您的索引:

if (foo>0) { 
    self.indexes = [NSArray arrayWithObjects:[NSNumber numberWithInt:Form_FirstName],[NSNumber numberWithInt:Form_NamePrefix],[NSNumber numberWithInt:Form_LastName],[NSNumber numberWithInt:Form_Email],[NSNumber numberWithInt:Form_Phone],nil]; 
} 
else { 
    self.indexes = [NSArray arrayWithObjects:[NSNumber numberWithInt:Form_FirstName],[NSNumber numberWithInt:Form_LastName],[NSNumber numberWithInt:Form_Email],[NSNumber numberWithInt:Form_Phone],nil]; 
} 

在其他地方,當你需要一個枚舉領域轉化爲一個索引:

NSInteger index = [self.indexes indexOfObject:[NSNumber numberWithInt:<Form Enumeration Value>]]; 
+0

有什麼建議嗎? – Chrizzz

+0

使用某種地圖。要麼由C++的STL映射提供(如果您知道C++),要麼使用「NSArray」展開自己的映射。我用一個使用NSArray的例子更新了答案。 – gschandler

+0

是的,謝謝。我想我可以做到這一點。它仍然更容易,然後多個tableviews :-) – Chrizzz

1

gschandler是正確的,你不能那樣做。從技術上講,你可以使用一個預處理命令

#if something 
    enum 
#endif 

但真正的問題是,爲什麼要做到以上。你認爲它會爲你做什麼?使用第一枚枚舉集沒有什麼壞處。誰在乎你是否不用使用 form_email?坐在那裏沒有任何傷害。

+0

原因是,我想在 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath中使用開關。根據if語句我想使用單元格或跳過單元格。我至少有3個不同的場景和更多的10個單元。 – Chrizzz

+0

這似乎也可以。但我認爲其他答案更傳統。不管怎樣,謝謝你。 – Chrizzz