objective-c - 如何获取 NSPopUpButton 选中的对象?

标签 objective-c cocoa nsmutablearray cocoa-bindings nspopupbutton

我正在上学生课:

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

我有一个 NSMutableArray 用于学生列表,我将它绑定(bind)到 NSPopUpButton,就像这样

内容:studentArray, arrangedObjects 内容值:studentArray, arrangedObjects, name

现在我可以像这样获取学生对象:

-(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];

最佳答案

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

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

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

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

关于objective-c - 如何获取 NSPopUpButton 选中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12075195/

相关文章:

ios - 在 NSUserDefault 中保存 NSMutableArray 给出 nil

objective-c - b/w addObject :dictionary and addObject:[dictionary copy] to an NSMutableArray? 有什么区别

objective-c - 为 Core Plot 触摸事件访问数据数组时崩溃

c++ - C++ 类是否管理 Objective-C 类的生命?

iphone - 更新前如何删除数据

objective-c - 无法弄清楚这个动态类型的事情

objective-c - 没有使用我的自定义 UIViewController 调用 ViewDidLoad

objective-c - NSProgressIndicator 中的标签/文本?

Cocoa shell命令权限

iphone - 将对象添加到数组不起作用,当我遍历数组时我看不到任何对象