Search code examples
objective-ccocoansmutablearraycocoa-bindingsnspopupbutton

how to get NSPopUpButton selected object?


I'm having a student class:

@interface student : NSObject{    
    NSString *name;
    NSDate *date;
}

and i have a NSMutableArray for list of students, and i bound it to a NSPopUpButton like this

content : studentArray, arrangedObjects content values : studentArray, arrangedObjects, name

now I can get the student object like this:

-(IBAction)studentPopupItemSelected:(id)sender
{ 
    NSPopUpButton *btn = (NSPopUpButton*)sender;

    int index = [btn indexOfSelectedItem];  
    student *std = [studentArray objectAtIndex:index];

    NSLog(@"%@ => %@", [std name], [std date]);
}

is there any way that i can get the student object directly from NSPopUpButton???? like:

NSPopUpButton *btn = (NSPopUpButton*)sender;
student *std = (student *)[btn objectValueOfSelectedItem];

Solution

  • The way you are doing it is fine. There is another way, but not necessarily better.

    Basically the popup button contains a menu, and in the menu there are menu items.

    On the menu item there is a property called representedObject, which you could use to create an association with a student.

    Therefore you can build your popup button manually by creating menu items, and adding them to your menu.