Search code examples
iosxcodeif-statementuipickerviewibaction

How to make an if statement using a pickerView


I have a pickerView and depending on the selection in that pickerView i want a button(calculate button) to perform one of two mathematical operations. The pickerView has one component, and 2 rows male, and female. If the user selects male, and then hits calculate button, i want the program to use one formula. If the user selects female, and then his the calculate button i want the program to use a different formula. I tired using.

-(IBaction)caclulate{

if ([pickerView isEqual:sexPickerView] ) {
    if ([objectAtIndex:0]) {
         "do formula 0"
}
if ([objectAtIndex:1){
  "do formula 1"
}
}

(the "do formula 0 and 1" are not actual code...i have mathematical formulas there, but those don't really matter to this question so i did that for short)

However, this got me two errors. pickerView undeclared and objectAtIndex undeclared. I am new to programming, so what i am trying to do is probably way off base...

Anyone know how to do what i need?

UPDATE

-(IBAction)calculate{

    if ([sexPickerView selectedRowInComponent:0]) {
    "do formula 0"
}

//female
 if ([sexPickerView selectedRowInComponent:1]) {
    "do formula 1"
 }
}

That is what i put, and now when I click the calculate button i get an error that says

[Session started at 2012-08-08 16:04:33 -0500.] 2012-08-08 16:05:26.580 CalorieAppFinal[4289:207] * Terminating app due to uncaught exception 'NSRangeException', reason: '* -[NSMutableArray objectAtIndex:]: index 1 beyond bounds [0 .. 0]'

When i take out the if statements and try each formula individually the app runs without a problem..


Solution

  • All you need is:

    [pickerView selectedRowInComponent:0];
    

    That will return you the row selected, in your case either 0 or 1

    As for pickerView not being declared, I'm not sure what pickerView you're trying to use, or where it should have been declared. If you already have a reference to sexPickerView just ignore that check and use sexPickerView outright

    EDIT

    In response to your error, the problem is the way you are attempting to check what is selected. You only have 1 component, so you can only call

    [sexPickerView selectedRowInComponent:0];
    

    You change that 0 to a 1 and it doesn't work. What that function returns is the 0 or 1 that you want to check. So your calculate function should look like this instead:

    -(IBAction)calculate{
    
        if ([sexPickerView selectedRowInComponent:0] == 0) {
        "do formula 0"
    }
    
    //female
     if ([sexPickerView selectedRowInComponent:0] == 1) {
        "do formula 1"
     }
    }