Cocoa 为什么NSpoupButton项会消失?

Cocoa 为什么NSpoupButton项会消失?,cocoa,nspopupbutton,Cocoa,Nspopupbutton,我有一个NSPopupButton,其选择索引绑定到NSWindowController子类中的属性。在IB中,按钮从几个项目开始。该属性的值来自NSUserDefaults,可能大于首次实例化时NSPopupButton中的项数。这将导致在列表末尾插入一个空白项。如果我将项目附加到按钮,自动创建的空白项目仍然存在。但当我做出选择时,它就消失了。如果在选择之前更改空白项的标题,该项仍然会消失。 我将问题归结为以下代码: @interface PopUpWindowController : NSW

我有一个NSPopupButton,其选择索引绑定到NSWindowController子类中的属性。在IB中,按钮从几个项目开始。该属性的值来自NSUserDefaults,可能大于首次实例化时NSPopupButton中的项数。这将导致在列表末尾插入一个空白项。如果我将项目附加到按钮,自动创建的空白项目仍然存在。但当我做出选择时,它就消失了。如果在选择之前更改空白项的标题,该项仍然会消失。

我将问题归结为以下代码:

@interface PopUpWindowController : NSWindowController {
    NSUInteger popUpValue;

    IBOutlet NSPopUpButton *popUp;
}

@property NSUInteger popUpValue; //popUp's Selected Index is bound to this property

-(IBAction)addItemsToPopUp:(id)sender;
-(IBAction)nameBlankItem:(id)sender;

@end


@implementation PopUpWindowController

@synthesize popUpValue;

-(id)init {
    if (self = [super initWithWindowNibName:@"PopUpWindow"]) {
        popUpValue = 5; //In my real program this comes from NSUserDefaults
    }
    return self;
}

-(IBAction)addItemsToPopUp:(id)sender {
    //Add three items to popUp
    NSUInteger lastNewItem = [popUp numberOfItems] + 3;
    for (NSUInteger newItem = [popUp numberOfItems]; newItem < lastNewItem; newItem++) {
        [popUp addItemWithTitle:[NSString stringWithFormat:@"%d", newItem + 1]];
    }
    self.popUpValue = 5;
}

-(IBAction)nameBlankItem:(id)sender {
    NSArray *items = [popUp itemArray];
    for (NSUInteger i = 0; i < [items count]; i++) {
        if (![[[items objectAtIndex:i] title] length]) {
            //item title is blank so set it to the item number
            [[items objectAtIndex:i] setTitle:[NSString stringWithFormat:@"%d", i + 1]];
        }
    }
}

@end
@接口PopUpWindowController:NSWindowController{
整数popUpValue;
IBOutlet nspoupbutton*弹出窗口;
}
@属性为整数popUpValue//弹出窗口的选定索引已绑定到此属性
-(iAction)addItemsToPopUp:(id)发送方;
-(iAction)nameBlankItem:(id)发件人;
@结束
@PopUpWindowController的实现
@综合popUpValue;
-(id)init{
if(self=[super initWithWindowNibName:@“PopUpWindow”]){
popUpValue=5;//在我的实际程序中,它来自NSUserDefaults
}
回归自我;
}
-(iAction)addItemsToPopUp:(id)发送方{
//在弹出窗口中添加三个项目
NSUInteger lastNewItem=[popUp numberOfItems]+3;
对于(NSUInteger newItem=[popUp numberOfItems];newItem
这是窗口首次出现时弹出的菜单(IB中有三个项目,分别名为“1”、“2”和“3”):

在调用
addItemsToPopUp:

在调用
nameBlankItem:

然后我再次调用了
additemstopoup:

现在我终于做出选择并再次弹出菜单:

4
去了哪里

在我的实际程序中,我确实希望菜单项为“1”。“n”(n由计算的NSArray中的项数定义)。我对其他方法持开放态度,但我希望解决方案继续使用NSpoupButton


(如果有必要,我在OS X 10.5.8下使用Xcode 3.1.2,但也在OS X 10.6.8下使用Xcode 3.2进行了测试。)

我通过将NSPopUpButton的内容值属性绑定到对象中的数组解决了这个问题。因此,我可以完全控制内容,而不是在幕后手动操作按钮的项目数组。

在调用
[self-willChangeValueForKey:@“popupValue”]
[self-didChangeValueForKey:@“popupValue”]
。请确保调用
popupValue=5
而不是
self.popupValue=5