7

我有一个学生类:如何获得NSPopUpButton选定的对象?

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

和我有一个NSMutableArray的学生名单,并且我把它绑定到NSPopUpButton这样

内容:studentArray,arrangedObjects 含量值:studentArray ,arrangedObjects,名

我可以让学生对象是这样的:

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

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

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

有没有什么办法可以直接从NSPopUpButton获取学生对象?像:

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

出于好奇,什么是触发'IBAction'列出? –

回答

7

你这样做的方式很好。还有另一种方式,但不一定更好。

基本上弹出按钮包含一个菜单,并在菜单中有菜单项。

在菜单项上有一个名为representObject的属性,您可以使用它来与学生创建关联。

因此,您可以通过创建菜单项并将它们添加到菜单中来手动构建弹出按钮。

3

我相信你这样做的方式是最好的。由于NSPopUpButton正在被你的数组填充,它实际上并不包含该对象,它只是知道它在哪里。个人而言,我会用

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

看着上NSPopUpButton的文档后,我敢肯定,这是获得对象的最有效方式。

3

我利用“NSMenuDidSendActionNotification”一旦用户选择了选择恰当的NSMenuItem在NSPopUpButton的NSMenu是被发送解决了这个问题。

您可以注册观察者在例如“awakeFromNib”像这样

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

如果你有几个NSPopUpButtons你可以注册为每一个观察者。 不要忘记在dealloc中删除观察者(S):

[[NSNotificationCenter defaultCenter] removeObserver: self]; 

在popUpSelectionChanged您可以检查标题,所以你知道哪个菜单实际发送通知。您可以在属性检查器中的Interface Builder中设置标题。

- (void)popUpSelectionChanged:(NSNotification *)notification {  
    NSDictionary *info = [notification userInfo]; 
    if ([[[[info objectForKey:@"MenuItem"] menu] title] isEqualToString:@"<title of menu of myPopUpButton>"]) { 
     // do useful things ... 
    } 
}