Search code examples
iosobjective-cuipickerview

Getting row without selection from UIPickerView


I have a pickerview that loads from a core data fetch on the view controller did load method. Everything works great, however I'm finding that I'm passing null values quite often, and that I'm having to spin the picker back and forth and click several times to get the value to hold.

I also have a problem if the user doesn't manually pick something, I need it to pass the value that the picker is on. I have a datepicker on the same viewcontroller and it passes whatever date it is sitting on without any problems. I'm probably overlooking something..any help would be appreciated

# pragma mark PickerView Section

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;  // returns the number of columns to display.
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return [profiles count];  // returns the number of rows
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    // Display the profiles we've fetched on the picker

    Profiles *prof = [profiles objectAtIndex:row];
    return prof.profilename;
}

//If the user chooses from the pickerview

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    selectedProfile = [[profiles objectAtIndex:row]valueForKey:@"profilename"];

}


# pragma mark Segue Section

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([[segue identifier] isEqualToString:@"resultsSegue"]) {

        ResultsVC *result = segue.destinationViewController;

        result.profileName = [NSString stringWithFormat:@"%@",selectedProfile];

        NSDate *selectedDate = [datePicker date];
        result.trialDate = selectedDate;

    }
}

Solution

  • You need to initialize selectedProfile to the 1st value in the picker. Do this in viewDidLoad. This way if the user never explicitly picks a value, the selectedProfile will be set to the 1st value by default.