tags:

views:

159

answers:

1

I'm trying to learn how to use the UIPickerView, and I don't know why my alert view always prints the first element in the array (picker), vs anything else. I have a button press defined for the picker as:

- (IBAction)buttonPressed {
    NSInteger row = [myPicker selectedRowInComponent:0];
    NSString *s = [myPickerData objectAtIndex:row];
    NSLog(@"%@", s);
    NSString *title = [[NSString alloc] initWithFormat:@"You selected, %@", s];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                message:@"Message"
                  delegate:nil
               cancelButtonTitle:@"ok"
               otherButtonTitles:nil];
    [alert show];
    [alert release];
    [title release];
}

my array defined as:

- (void)viewDidLoad {
    [super viewDidLoad];
    NSArray *array = [[NSArray alloc] initWithObjects:@"0", @"1", @"2", nil];
    self.myPickerData = array;
    [array release];
}

I log the outputs when the picker is changed, and the values do get changed to 0, 1, 2, accordingly.

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    NSLog(@"%@", [myPickerData objectAtIndex:row]);
}

But the alert view never works. So I'm unsure what I am doing wrong here.

+1  A: 

I suspect you are missing a connection in your nib file, specifically from the myPicker outlet to the UIPickerView instance. If that were the case, myPicker would be nil, and so the line

NSInteger row = [myPicker selectedRowInComponent:0];

would always set row to 0, which explains why you are always displaying the first item in your array.

Aside from checking your nib file, you can also confirm this by setting a breakpoint in the buttonPressed method and checking to see if myPicker is nil.

You do have a connection from your UIPickerView's delegate/dataSource outlet to your controller class, which is why your delegate methods are being called. But you need a connection in the other direction for your button method to work properly.

benzado