我对 cocoa 开发非常陌生,我正在尝试加载一个窗口。 我会解释我的问题。
当用户单击菜单项时,我使用以下代码加载窗口
if ( !cadastroContasController )
{
cadastroContasController = [[cadastroContas alloc]init];
[cadastroContasController SetMenuItem:sender];
}
if ( ![[cadastroContasController window] isVisible] )
{
NSLog(@"!isVisible");
[cadastroContasController showWindow:nil];
}
我的 cadastroContas 类看起来像这样:
@interface cadastroContas : NSWindowController
{
NSMenuItem *mnuCommand;
IBOutlet NSComboBox *cmbSelecao;
IBOutlet NSTextField *txtNome;
IBOutlet NSTextField *txtSaldoInicial;
IBOutlet NSTextField *txtAnotacoes;
}
- (void)windowDidBecomeKey:(NSNotification *)notification;
- (BOOL)windowShouldClose:(id)sender;
- (void)windowWillClose:(NSNotification *)notification;
- (void)SetMenuItem:(NSMenuItem*) menu;
- (NSMenuItem*) MenuItem;
@end
实现是
@implementation cadastroContas
-(void)windowDidLoad
{
NSLog(@"windowDidLoad");
[mnuCommand setState:NSOnState];
}
-(id)init
{
self = [super initWithWindowNibName:@"cadastroContas"];
NSLog(@"Init self=%p", self);
return self;
}
-(void)dealloc
{
NSLog(@"Dealoc=%p", self);
[super dealloc];
}
- (void)windowDidBecomeKey:(NSNotification *)notification
{
NSLog(@"windowDidBecomeKey window=%p", [self window]);
}
- (BOOL)windowShouldClose:(id)sender
{
NSLog(@"windowShouldClose Window=%p", [self window]);
NSLog(@"mnuComando=%p GetMenuItem=%p", mnuCommand, [self MenuItem] );
if ( mnuCommand )
{
[mnuCommand setState:NSOffState];
}
return YES;
}
- (void)windowWillClose:(NSNotification *)notification
{
NSLog(@"windowWillClose Window=%p", [self window]);
NSLog(@"mnuCommand=%p GetMenuItem=%p", mnuCommand, [self MenuItem] );
[self dealloc];
}
- (void)SetMenuItem:(NSMenuItem*) menu
{
mnuCommand = menu;
}
- (NSMenuItem*) MenuItem
{
return mnuCommand;
}
@end
当点击菜单时,我收到两条消息“Init”,我不知道为什么。 示例:
[2223:a0f] Init self=0x10014fe40
[2223:a0f] Init self=0x10011f5a0
第二条消息让“[cadastroContasController SetMenuItem:sender];
”无用。
所以,我需要帮助来了解发生了什么......
另一件事,[[cadastroContasController window]
总是返回NULL(0x0)
!!,但在我的 Controller 内我可以处理它(它不是空的) .
最佳答案
这意味着您启动了两个实例,如 self
指针的记录所示:请注意,两条消息之间的值不同。
您可以使用仪器中的分配仪器来查看导致每个窗口 Controller 被实例化的原因。
通常,当您在 Nib 中创建其中一个并在代码中创建另一个时,就会发生此问题。对于窗口 Controller ,您在代码中创建的 Controller 应该是其 Nib 的所有者;您不应该创建另一个窗口 Controller 作为 Nib 中的对象。
Another thing,
[[cadastroContasController window]
is always returningNULL(0x0)
!!, but inside my controller i can handle it (it isn't null).
您将其 window
导出设置为该窗口的窗口 Controller 是返回非nil
的窗口 Controller 。您未设置 window
导出的窗口 Controller 是返回 nil
的窗口 Controller 。
根据我上面所说,删除您在 Nib 中创建的窗口 Controller 后,您应该将文件所有者的window
导出连接到该窗口。
关于cocoa - NSWindowController 子类 - Init 被调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4981913/