xcode For Loop 为我重复检查变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5134759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 03:43:14  来源:igfitidea点击:

For Loop to do repetitive checking of variables for me

xcodeloopsfor-looptask

提问by ArthDent

NSArray *test = [NSArray arrayWithObjects:@"22", @"3", @"22", @"5", @"1", @"0", @"2", nil];

NSArray *test2 = [NSArray arrayWithObjects:@"21", @"2", @"20", @"5", @"1", @"9", @"2", nil];

for(int i = 0; i < 7; i++) {

   if ([test objectAtIndex:i] == [test2 objectAtIndex:i]); {

testVariable = testVariable + 1; 
    }

}    

NSLog(@"%i", testVariable);    

I tried the above code to test comparison of variables but it returns 7 when it should return 3. Do I need to somehow retrieve and store each array object in a local variable and compare thos against each other? Or can I do something more direct like what I tried above. Arrays are very interesting. :)

我尝试了上面的代码来测试变量的比较,但是当它应该返回 3 时它返回 7。我是否需要以某种方式检索每个数组对象并将其存储在一个局部变量中并相互比较?或者我可以做一些更直接的事情,就像我上面尝试的那样。数组非常有趣。:)

UPDATE:

更新:

Got it to work with NSInteger.. :) Guess I was comparing objects and not the actual integer numbers before..

让它与 NSInteger 一起工作.. :) 猜猜我在比较对象而不是之前的实际整数..

回答by godlark

You can use preprocesor

您可以使用预处理器

#define variable(name,number) {name##number}

and later in the loop

然后在循环中

for (int a = 1; a <= 53; a++) {    
    if ((variable(taken,a) == 2) && (variable(hidden,a) == 2)) {
        //Do something
    } 
}

回答by Jon Skeet

The simple answer is not to use different variables. Use a collection or an array instead. Then you could have:

简单的答案是不要使用不同的变量。改用集合或数组。那么你可以有:

if (taken[a] == 2 && hidden[a] == 2) {
    ...
}

Think of using an array whenever you find yourself putting numeric suffixes on variables of the same type and prefix.

每当您发现自己将数字后缀放在相同类型和前缀的变量上时,请考虑使用数组。