我有一个自定义类,它应该从 nib 文件加载窗口。 当我加载 nib 文件时,一切看起来都很好,除了 IBOutlet 未连接,即 nil。 IBActions 工作正常,当它们被调用时,IBOutlet 不再为零。
该类作为对象添加到 IB 中的 Nib ,显然所有内容都已连接。
它是文件的所有者和委托(delegate)人
加载 Nib 时,仅当设置了“启动时可见”时才会出现该窗口。
无论我在哪里加载 Nib 并立即或几秒钟后尝试访问 IBOutlet 都没有关系。
这一定是一些非常琐碎的事情......
更新2:我上传了一个更简单的试用项目:Trial Project2
预期行为:加载时 Window2 标题更改为“标题已更改 x 次”。它只有在按下按钮后才开始工作,即 IBOutlet 不再为零。
最佳答案
最大的变化是子类化 NSWindowController 以创建 MyClass。这样,您只需在窗口加载后尝试操作关闭按钮。您的代码足够小,我认为最好简单地发布更改:
TrialProjectAppDelegate.m
#import "trialProjectAppDelegate.h"
@implementation trialProjectAppDelegate
@synthesize window;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
myclass = [[MyClass alloc] init];
// Note that I'm forcing the window to load here.
(void) [myclass window];
}
@end
MyClass.h
#import <Cocoa/Cocoa.h>
@interface MyClass : NSWindowController
{
IBOutlet NSButton *dismissButton;
}
- (IBAction)closeNaggingWindow:(id)sender;
- (void)disableDismissButton;
@end
MyClass.m
#import "MyClass.h"
@implementation MyClass
- (id)init
{
if ((self = [super initWithWindowNibName:@"Window"]) != nil)
{
}
return self;
}
- (void)disableDismissButton
{
[dismissButton setEnabled:NO];
[dismissButton setTitle:@"Closing enabled in 5 sec"];
[self performSelector:@selector(enableDismissButton:) withObject:nil afterDelay:5];
}
- (IBAction)enableDismissButton:(id)sender
{
[dismissButton setEnabled:YES];
[dismissButton setTitle:@"Close"];
}
- (IBAction)closeNaggingWindow:(id)sender
{
[[self window] close];
[self autorelease];
}
- (void)awakeFromNib
{
[self disableDismissButton];
}
@end
最后,在您的 Window.xib 文件中,放弃 naggingWindow 导出并将您的窗口连接到 NSWindowController 提供的窗口导出。
关于xcode - Nib 的 IBOutlet 未连接(nil),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7568255/