可可编程,设置代表

sim*_*sid 7 xcode cocoa objective-c interface-builder

我正在从iOS转向Cocoa,并试图搞砸我的前几个程序.我认为添加NSComboBox到我的表单会很简单,那部分就是.我添加<NSComboBoxDelegate, NSComboBoxDataSource>到我的界面,两个数据回调和通知程序:

@interface spcAppDelegate : NSObject <NSApplicationDelegate,
                      NSComboBoxDelegate, NSComboBoxDataSource>

- (id)comboBox:(NSComboBox *)aComboBox objectValueForItemAtIndex:(NSInteger)index;
- (NSInteger)numberOfItemsInComboBox:(NSComboBox *)aComboBox;

- (void)comboBoxSelectionDidChange:(NSNotification *)notification;

@end
Run Code Online (Sandbox Code Playgroud)

我控制将组合框拖到app delegate(这是我的简单默认应用程序中唯一的类)并连接了委托和数据源,但这些事件都没有触发.我认为app委托是正确的,但由于它没有触发,我也尝试了"文件所有者"和"应用程序".我不认为那些会起作用而他们没有.

什么是NSComboBox在Cocoa应用程序中连接代理/数据源的正确方法?

谢谢!

NSG*_*God 15

如果您已在spcAppDelegate.m文件中实际实现了这些方法,则可能需要仔细Uses Data Source检查NSComboBox在Interface Builder中的nib文件中检查的方法:

在此输入图像描述

请注意,在我创建的快速测试项目中,默认情况下未设置它.在没有设置该复选框的情况下运行应该在启动应用程序时将以下内容记录到控

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
Run Code Online (Sandbox Code Playgroud)

虽然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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

示例项目:http://github.com/NSGod/NSComboBox.