Question

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];
Was it helpful?

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.

OTHER TIPS

I believe the way you are doing it is the best. Since the NSPopUpButton is being populated by your array it does not actually contain the object, it just knows where it is. Personally I would use

-(IBAction)studentPopupItemSelected:(id)sender {
     student *std = [studentArray objectAtIndex:[sender indexOfSelectedItem]];
     NSLog(@"%@ => %@", [std name], [std date]);
}

After looking at the documentation on NSPopUpButton I'm sure this is the most efficient way of obtaining the object.

I solved the problem by utilising the "NSMenuDidSendActionNotification" that gets sent once the user has chosen the approriate NSMenuItem in the NSMenu of the NSPopUpButton.

You can register the observer in e.g. "awakeFromNib" like this

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(popUpSelectionChanged:)
                                             name:NSMenuDidSendActionNotification
                                           object:[[self myPopUpButton] menu]];

If you have several NSPopUpButtons you can register an observer for each one. Don't forget to remove the observer(s) in dealloc:

[[NSNotificationCenter defaultCenter] removeObserver: self];

In popUpSelectionChanged you can check the title so you know which menu actually sent the notification. You can set the title in Interface Builder in the Attributes Inspector.

- (void)popUpSelectionChanged:(NSNotification *)notification {    
    NSDictionary *info = [notification userInfo];
    if ([[[[info objectForKey:@"MenuItem"] menu] title] isEqualToString:@"<title of menu of myPopUpButton>"]) {
        // do useful things ...
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top