xcode NSArray 索引 1 超出空数组的界限

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13260538/
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-15 02:02:06  来源:igfitidea点击:

NSArray index 1 beyond bounds for empty array

objective-ciosxcode

提问by user1491987

-(IBAction)someMethod:(UIStepper *)sender{
    int x=sender.value; //This is an integer from 0-8;
    NSLog(@"%f",sender.value);
    NSArray *rpmValues = [[NSArray alloc]initWithObjects:@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i", nil];
    if (x<=[rpmValues count]) {

        myLabel.text = [rpmValues objectAtIndex:x];
    }
    NSLog(@"%i",[rpmValues count]);
}

Above is my code, what I want to do is to change UILabel display by changing UIStepper. This is very straight forward. But when I change press the stepper value, it crashes:

上面是我的代码,我想要做的是通过改变UIStepper来改变UILabel的显示。这是非常直接的。但是当我改变按下步进值时,它崩溃了:

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -   [__NSArrayM objectAtIndex:]: index 1 beyond bounds for empty array'
*** First throw call stack:

And the [rpmValue count] is 9. I really got confused. Can anyone help me?

而 [rpmValue count] 是 9。我真的很困惑。谁能帮我?

回答by WDUK

That code seems fine (see my comment on the question); your problem could arise from the use of

该代码看起来不错(请参阅我对问题的评论);您的问题可能是由于使用

if (x<=[rpmValues count]) {

This will include the count of the array, which exceeds the index range by one. Use

这将包括数组的计数,该计数超出索引范围一。用

if (x < [rpmValues count]) {

回答by Tommy

At the very least if (x<=[rpmValues count])should be if (x<[rpmValues count]). Otherwise if you have an array with, say, two entities then you're allowing yourself to access indices 0, 1 and 2 — three possibilities in total.

至少if (x<=[rpmValues count])应该是if (x<[rpmValues count])。否则,如果您有一个包含两个实体的数组,那么您将允许自己访问索引 0、1 和 2 — 总共三种可能性。

Is it possible you've set a maximumValueon your stepper of '9' based on similar logic?

您是否可能maximumValue根据类似的逻辑在“9”的步进器上设置了 a ?