Reputation: 751
-(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?
Upvotes: 0
Views: 6701
Reputation: 100622
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?
Upvotes: 0
Reputation: 19030
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]) {
Upvotes: 4