【问题标题】:Incorrect Delegate for Controls on Main Application Window主应用程序窗口上的控件委托不正确
【发布时间】: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的实现者selfAppDelegate。相比之下,在模态对话框中,selfFile's Owner 是同一个对象,派生自 NSWindowController

因此,结果是我没有为主窗口中的控件分配正确的委托 - 我该怎么做?

【问题讨论】:

  • Doh - 我的最后一行可以改写为“如何让 App Delegate 成为 NSTextField 的代表”。答案就是连接它们而不是文件的所有者!

标签: xcode delegates interface-builder


【解决方案1】:

你能发布一些代码吗?

使用委托时,请确保您指定一个类实现所需的协议。

@interface MyClass : NSObject &lt;SomeProtocol&gt;

还要确保您正在创建一个属性来存储委托。

@property (strong, nonatomic) id&lt;SomeProtocol&gt; delegate;

这是:

请注意,虽然 NSControl 定义了委托方法,但它并没有 本身有一个代表。任何使用这些方法的子类都必须有 一个委托以及获取和设置它的方法。此外,一个正式的 委托协议 NSControlTextEditingDelegate 协议还定义了 控制委托使用的委托方法。 ...

其中包括:controlTextDidBeginEditing:、controlTextDidChange: 和 controlTextDidEndEditing:

【讨论】:

  • 添加了代码,也许想出了如何让它工作。它确实有效,但这是正确的方法吗?这会导致任何有害的副作用吗?
【解决方案2】:

哦,哇 - 在为我的问题添加更多细节时,我想我找到了答案。无需从文本字段委托拖动到文件所有者,只需拖动到代表 App Delegate 的蓝色立方体!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-09
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 2017-12-03
    • 1970-01-01
    相关资源
    最近更新 更多