2012-03-06 51 views
3

試圖與陣列工作的陣列錯誤,但它給了我「語句需要整數類型的表達式(‘身份證’無效)」就在開關聲明。怎麼了?「語句需要整型的表達」與switch語句和字符串

NSArray count = [NSArray arrayWithObjects: @"1", @"2", @"3", @"4", @"5", @"6", @"7", nil];  

switch ([count objectAtIndex: myIndex]) { 
    case 1: 
     NSLog(@"One"); 
     break; 
    case 2: 
     NSLog(@"Two"); 
     break; 
    case 3: 
     NSLog(@"Three"); 
     break; 
    default: 
     break; 
} 
+6

我認爲你缺少基本的編程知識......我的建議,從零做起,不要試圖學習一切在一個星期。此外,不要使用教程來學習,獲得一本書或去上課(如果可能的話)。 – EmilioPelaez 2012-03-06 05:11:58

回答

9

switch語句僅適用於整型。你的數組包含NSString對象。轉換您從陣列得到這樣一個整數NSString

NSArray count = [NSArray arrayWithObjects: @"1", @"2", @"3", @"4", @"5", @"6", @"7", nil]; 

NSString *obj = [count objectAtIndex: myIndex]; 
switch ([obj intValue]) { 
    case 1: 
     NSLog(@"One"); 
     break; 
    case 2: 
     NSLog(@"Two"); 
     break; 
    case 3: 
     NSLog(@"Three"); 
     break; 
    default: 
     break; 
} 
+0

ooooh我也喜歡這個 – QED 2012-03-06 04:21:18

+0

爲什麼不把NSNumbers存儲在數組中?將數字存儲爲字符串有點脆弱...... – bryanmac 2012-03-06 04:31:50

+0

@bryanmac這樣做會更有意義......但NSNumber仍然是一個對象,所以您仍然必須提取在switch語句中使用的整數值。 – highlycaffeinated 2012-03-06 04:34:42

2

您正在創建一個字面NSString的數組,並在整數上執行case語句。您只能切換整型。

問題是arrayWithObjects創建一個NSObject派生對象的數組,您無法切換對象(id)。

如果你想存儲一個數字數組,那麼一個選項是存儲NSNumber對象,而不是依賴存儲希望是數字的字符串的脆弱性。這工作:

NSArray *arr = [NSArray arrayWithObjects: [NSNumber numberWithInt:1], [NSNumber numberWithInt:2], nil]; 

switch ([[arr objectAtIndex:1] intValue]) { 
    case 1: 
     NSLog(@"1"); 
     break; 

    case 2: 
     NSLog(@"2"); 
     break; 

    default: 
     break; 
} 

它輸出:

2012-03-05 23:23:46.798 Craplet[82357:707] 2 
+0

我意識到另一個問題是我在 - (void)viewDidLoad方法中啓動了我的數組,但我無法從其他方法訪問它。你如何創建一個全局數組(全局變量)? – NoobDev4iPhone 2012-03-06 05:53:41

+0

簽出單身模式。 – bryanmac 2012-03-06 06:32:39

+0

http://stackoverflow.com/questions/145154/what-does-your-objective-c-singleton-look-like – bryanmac 2012-03-06 06:33:15

1

[count objectAtIndex:]返回一個ID(又名對象),這在你的具體情況將是一個NSString的,在任何情況下,它不是一個整數,你的情況下,表達期待。您需要[[count objectAtIndex:myIndex] intValue]將NSString轉換爲整數。

1

您的數組對象是NSStrings,而不是ints。你想要完成的是什麼?

,你可以:

NSString *str = [count objectAtIndex:myIndex]; 
if ([str isEqualToString:@"1"]) NSLog(@"One"); 
else if ... // etc 

更妙的是:

static NSString *one = @"1"; 
static NSString *two = @"2"; 
// etc 

NSArray *count = [NSArray arrayWithObjects:one, two, ... nil]; 

NSString *str = [count objectAtIndex:myIndex]; 

if (str == one) NSLog(@"One"); // this works because now 'str' and 'one' are the same object 
else if ... // etc