【发布时间】:2013-02-07 23:45:31
【问题描述】:
我正在 XCode 4.6 中开发应用程序。
要从 NSTextField 控件获取文本更改通知,我:
- 将 NSTextField 控件放在窗口上。
- 通过在 IB 中右键单击将控制委托连接到文件所有者,从委托拖动到文件所有者。
- 在窗口类中实现 controlTextDidChange。
对于应用程序,窗口类是我的 AppDelegate,文件的所有者是 NSApplication。对于模态对话框,窗口类 NSWindowController 和 File's Owner 属于同一类型。
如果我在 AppDelegate 类的 controlTextDidChange 中设置断点,它永远不会触发。如果我使用模态对话框执行相同的过程,它可以正常工作。
我知道在主应用程序窗口的情况下,控件的委托不是我的 AppDelegate。
在主窗口中连接我的控制委托时我做错了什么?我一定错过了一些简单的东西。 File's Owner 是为控件设置的正确代表吗?
任何帮助将不胜感激。
这里是一些要求的代码。
// AppDelegate.h
// SimpleApplication
#import <Cocoa/Cocoa.h>
#import "SimpleTest/SimpleTest.h"
@interface AppDelegate : NSObject <NSApplicationDelegate>
@property (assign) IBOutlet NSWindow *window;
@property (assign) IBOutlet NSTextField *textField;
@end
// AppDelegate.m
// SimpleApplication
#import "AppDelegate.h"
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Not much to do here for now.
}
// Breakpoint set in this function never fires.
- (void)controlTextDidChange:(NSNotification *)obj
{
NSMutableString* description= [[NSMutableString alloc] init];
id aDelegate= [_textField delegate];
Class delegateClass= [aDelegate class];
[description setString:[delegateClass description]];
[description release];
}
// To provide some information about the delegates.
- (IBAction)textChange:(id)sender
{
NSTextField* theTextField= (NSTextField*)sender;
NSMutableString* description= [[NSMutableString alloc] init];
id aDelegate= [theTextField delegate];
Class delegateClass= [aDelegate class];
[description setString:[delegateClass description]];
[description release];
}
@end
这里是主窗口中 NSTextField 的右键信息截图 -
身份检查器将 File's Owner 显示为 NSApplication,当我在 textChange 中放置断点并在文本字段中点击 return 时,我在调试器中看到了这一点。而controlTextDidChange的实现者self是AppDelegate。相比之下,在模态对话框中,self 和 File's Owner 是同一个对象,派生自 NSWindowController。
因此,结果是我没有为主窗口中的控件分配正确的委托 - 我该怎么做?
【问题讨论】:
-
Doh - 我的最后一行可以改写为“如何让 App Delegate 成为 NSTextField 的代表”。答案就是连接它们而不是文件的所有者!
标签: xcode delegates interface-builder