0
-(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:

*** 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?

6
  • 2
    Other than the if statement needing to use < and not <=, this code looks OK. Are you 100% sure the error is coming from this code and not some other place? Commented Nov 6, 2012 at 22:42
  • Setting int x manually to 1 seems to work for me, can you try this? Your NSLog statement is wrong, what does NSLog(@"%d",sender.value); print? Something else must be causing the problem. Commented Nov 6, 2012 at 22:42
  • The problem is when x = [rpmValues count]. Getting an object at that index does not work as index starts from 0. Commented Nov 6, 2012 at 22:43
  • You shouldn't be able to get this error message from the code you posted -- I tried it out and it worked fine up until the last item which can be fixed like the comments have said. So, I believe your error is elsewhere. Commented Nov 6, 2012 at 23:00
  • Also, your error is pointing to a mutable array, and rpmValues is immutable. You should add an exception breakpoint to your project, so the line where the error occurs will be highlighted. Commented Nov 6, 2012 at 23:15

2 Answers 2

4

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]) {
Sign up to request clarification or add additional context in comments.

Comments

0

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.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.