UIPickerView NSInvalidArgumentException', reason: '-[__NSCFString superview]: unrecognized selector sent to instance

StackOverflow https://stackoverflow.com/questions/15303020

Question

I am a rookie with Objective C and Xcode and am trying to learn one step at a time. I have been scratching my head on a particular issue for days and am having a very hard time finding a solution. I am making a UIPickerVIew app that uses a dictionary to populate the picker. The arrayStates is a state that goes into a the left component, and the arrayCities are cities that are in that state in which are keys of State. The cities go in the right component. I think have the issue narrowed down to a block of code.. It is when I go to populate the picker with the values where it crashes. I can comment out this block of code and it will run just fine (only with question marks as the text in the picker). I get this error:

NSInvalidArgumentException', reason: '-[__NSCFString superview]: unrecognized selector sent to instance

Here is the block of code from my .m file causing the error:

-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:    (NSInteger)component reusingView:(UIView *)view {

if (component == 0) {
   return [arrayStates objectAtIndex:row];
}
else {
UILabel *lblCity=[[UILabel alloc] initWithFrame:CGRectMake(5,0,220,50)];
lblCity.text= [arrayCities objectAtIndex:row];
lblCity.backgroundColor = [UIColor clearColor];
lblCity.font = [UIFont boldSystemFontOfSize:18];
return lblCity;
}

}

Below is what I changed my code to and it is running great! Thank you for the fast and accurate responses!!

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component

{

if (component == 0)
{
   return [arrayStates objectAtIndex:row];
}
else
{
  return [arrayCities objectAtIndex:row];
}

}
Was it helpful?

Solution

You're getting this error, because you're returning a string if the component is 0. You probably want to use pickerView:titleForRow:forComponent: instead of viewForRow, and just return the string from your arrays, rather than making a label for the cities.

OTHER TIPS

What that error means is that you are passing an NSString based class where you should be passing a UIView based class.

I don't see anything here that would suggest that actually happening so I expect its this return [arrayStates objectAtIndex:row]. You need a be returning a UIView so unless arrayStates contains nothing but UIView's that is the base of your crash. How and where you fix it can be a bit more complicated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top