如果您已经在spcAppDelegate.m
文件中实现了这些方法,您可能想要再次检查Interface Builder中nib文件中的NSComboBox
是否已选中Uses Data Source
:
![enter image description here](https://istack.dev59.com/BRdTl.webp)
请注意,在我创建的一个快速测试项目中,默认情况下未设置该复选框。如果在没有设置该复选框的情况下运行,则启动应用程序时会将以下内容记录到控制台:
NSComboBox[2236:403] *** -[NSComboBox setDataSource:] should not be called when
usesDataSource is set to NO
NSComboBox[2236:403] *** -[NSComboBoxCell setDataSource:] should not be called
when usesDataSource is set to NO
虽然NSComboBox类参考文档有些帮助,但当我刚开始学习时,我发现如果有附带的指南与该类链接,这更有助于理解如何在实践中使用该类。如果您查看Companion Guide中的NSComboBox
类参考文档顶部,您将看到组合框编程主题。
要设置使用数据源的组合框,您可以使用以下内容:
spcAppDelegate.h:
#import <Cocoa/Cocoa.h>
@interface spcAppDelegate : NSObject <NSApplicationDelegate,
NSComboBoxDelegate, NSComboBoxDataSource> {
IBOutlet NSWindow *window;
IBOutlet NSComboBox *comboBox;
NSMutableArray *comboBoxItems;
}
@property (assign) IBOutlet NSWindow *window;
@end
spcAppDelegate.m:
#import "spcAppDelegate.h"
@implementation spcAppDelegate
@synthesize window;
- (id)init {
if ((self = [super init])) {
comboBoxItems = [[NSMutableArray alloc] initWithArray:
[@"Cocoa Programming setting the delegate"
componentsSeparatedByString:@" "]];
}
return self;
}
- (void)dealloc {
[comboBoxItems release];
[super dealloc];
}
- (NSInteger)numberOfItemsInComboBox:(NSComboBox *)aComboBox {
return [comboBoxItems count];
}
- (id)comboBox:(NSComboBox *)aComboBox objectValueForItemAtIndex:(NSInteger)index {
if (aComboBox == comboBox) {
return [comboBoxItems objectAtIndex:index];
}
return nil;
}
- (void)comboBoxSelectionDidChange:(NSNotification *)notification {
NSLog(@"[%@ %@] value == %@", NSStringFromClass([self class]),
NSStringFromSelector(_cmd), [comboBoxItems objectAtIndex:
[(NSComboBox *)[notification object] indexOfSelectedItem]]);
}
@end
示例项目:http://github.com/NSGod/NSComboBox。