0

I have the following code and am getting error at NSString *weight line:

* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[NSArray objectAtIndex:]: index 2 beyond bounds [0 .. 1]' - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
       NSArray *array;
       array = [[NSArray alloc]initWithObjects:@"0", @"1/2", nil];           
       UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 37)];
       NSString *weight = [[array objectAtIndex:row] stringValue];
       label.text = [NSString stringWithFormat:@"%@", weight]
1
  • I've added the method title. It is a UIPickerView Commented Apr 19, 2011 at 20:26

3 Answers 3

2

The problem is right there in the error message. What's wrong is that you have an array with 2 things in it (the strings "0" and "1/2"), and you're asking it for index 2, which is invalid. (Only 0 and 1 would be valid).

You don't show how you're getting row but that's your problem. It's too big.

Sign up to request clarification or add additional context in comments.

2 Comments

@Faisal: Your problem is the same. You have more rows in your picker than you have strings in your label array. How that happened is a different question, and you might want to ask it as a separate page here, or give enough context so that people can help you.
ok thanks, i think the problem is in my - (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component method
0

The value of "row" is 2, but your array only has 2 elements, meaning the maximux value of row should only ever be "1"

Comments

0

You have 2 objects in your array and it looks like from your exception that row is 2 which will try to access a 3rd object. In your situation where you have only 2 objects declared in the same method why not use a switch statement and log/assert on the default case? Ultimately you need to make sure you tell the picker the right amount of columns for the right component.

1 Comment

Updated my answer with recommendations

Your Answer

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