Why Is My NSLog Crashing? (NSMutable Array and UIPickerView Related)
I have a UIPickerView with 2 components.
Here is the arrays loading into it:
pickerArray = [[NSMutableArray alloc] initWithCapacity:700];
for ( int i = 0 ; i <= 1000 ; ++i)
[pickerArray addObject:[NSString stringWithFormat:@"%d", i]];
pickerArrayHalf = [[NSMutableArray alloc]initWithCapacity:2];
[pickerArrayHalf addObject:@".0 lb"];
[pickerArrayHalf addObject:@"1/2 lb"];
Here are delegate methods:
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView
{
if (thePickerView.tag==1)
{
return 2;
}
else
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component
{
if (thePickerView.tag==1)
{
if (component == 0)
return [pickerArray count];
if (component == 1)
return [pickerArrayHalf count];
}
else
return [pickerArray count];
}
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if (thePickerView.tag==1)
{
NSLog(@"Selected weight 1: %@. Index of array: %i", [pickerArray objectAtIndex:row], row);
NSLog(@"Selected weight 2: %@. Index of array: %i", [pickerArrayHalf objectAtIndex:row], row);
}
else
{
NSLog(@"Selected rep number: %@. Index of array: %i", [pickerArray objectAtIndex:row], row);
}
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
if (pickerView.tag==1)
{
if (component == 0)
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 37)];
int weight = [[pickerArray objectAtIndex:row] intValue];
label.text = [NSString stringWithFormat:@"%d", weight];
label.textAlignment = UITextAlignmentCenter;
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont boldSystemFontOfSize:30];
[label autorelease];
return label;
}
else
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 37)];
label.text = [pickerArrayHalf objectAtIndex:row];
label.textAlignment = UITextAlignmentCenter;
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont boldSystemFontOfSize:30];
[label autorelease];
return label;
}
}
When scrolling, the app is crashing at line开发者_C百科: NSLog(@"Selected weight 2: %@. Index of array: %i", [pickerArrayHalf objectAtIndex:row], row);
Any ideas why?
Your pickerview has two components / columns. You have to handle scrolling each component separately. In your case, you're printing out the value at the row index for both components even though the method is specific to a component.
So if I were to scroll to the tenth row in the first column, you're attempt to print out the tenth element of both data sources. Given that the data source for the second column only appears to have 2 elements, you're application is going to crash whenever the first column is scrolled beyond the first two values.
You need to implement your logic based on the given component as you do in the numberOfRowsInComponent: method.
精彩评论