2012-03-06 45 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