Cocoa:辅助.xib中的Button Control(从MainWindowController加载)无法调用其Action

时间:2016-11-12 22:29:02

标签: objective-c xcode cocoa

使用目标c在MacOs 10.10下使用Xcode 7.3的简单测试应用程序。

AppDelegate.h
    @property MainWindowController *myMainWindowController;

AppDelegate.m
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    _myMainWindowController = [[MainWindowController alloc] initWithWindowNibName:@"MainWindowController"];

    [_myMainWindowController showWindow:self];
}

MainWindowController.xib只是带有主视图的MainWindow

MainWindowController.h
    @property IBOutlet NSView * mainView;  //hooked up to the View in the MainWindowController.xib

MainWindowController.m
- (void)windowDidLoad {
    [super windowDidLoad];
    MyXib* vc = [[MyXib alloc] initWithNibName:nil bundle:nil];
    [_mainView addSubview:[vc view] ];
}

MyXib是在Xcode中创建的,作为NSViewController的子类。它的View中有一个Button对象。

MyXib.h

@interface MyXib : NSViewController
- (IBAction)buttonPushed:(id)sender;

MyXib.m

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (IBAction)buttonPushed:(id)sender{
    NSLog(@"buttonPushed");
}

theButton的动作连接到buttonPushed。

运行应用程序时,将按预期显示用户界面。但是当单击Button时,程序崩溃而没有调用buttonPushed方法。有时调试窗口会显示堆栈爬行,其结尾类似于" [NSURL buttonPushed:]:无法识别的选择器发送到实例.."

我已经调用了viewDidLoad,awakeFromNib和init。这些调用中的断点似乎表明根据文档逻辑上的行为。

1 个答案:

答案 0 :(得分:0)

感谢Willeke!以下是维护引用的修复:

#import "MainWindowController.h"

@interface MainWindowController ()
@property IBOutlet NSView * mainView;
@property  MyXib* vc; // maintain a reference!

@end

@implementation MainWindowController

- (void)windowDidLoad {
    [super windowDidLoad];
    //create an NSViewController and use it to load the xib
    _vc = [MyXib alloc];
    _vc = [_vc initWithNibName:nil bundle:nil];
    [_mainView addSubview:[_vc view] ];
}

@end