Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

macos - Loading main window at applicationDidFinishLaunching in Cocoa Application

In a Cooca Application the MainMenu.xib is setup for you in the standard template. This nib has been setup with the application delegate too. In the info.plist the key "Main nib file bas ename" sets the nib file to load at startup.

I want the application to start if possible without a nib, I want to load the MainMenu.xib at applicationDidFinishLaunching in the application's main delegate.

Is it possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First, comment out NSApplicationMain in supporting files -> main.m. NSApplicationMain() loads the main nib mentioned in your Info.plist, so skip it. Instead, setup the app and delegate and run the application:

int main(int argc, const char * argv[])
{
    //return NSApplicationMain(argc, argv);

    @autoreleasepool {
        NSApplication * application = [NSApplication sharedApplication];
        MYAppDelegate* appDelegate = [[MYAppDelegate alloc] init];

        [application setDelegate:appDelegate];
        [application run];
    }

    return EXIT_SUCCESS;
}

Then, in the app delegate's applicationDidFinishLaunching: function, call something similar to createMainWindow:

- (void)createMainWindow
{
    self.wincon = [[MYCustomWindowController alloc] initWithWindowNibName:@"MainMenu"];
    self.window = self.wincon.window; // window property in appdelegate created for single-view app
    // Also had to connect About: to application's orderFrontStandardAboutPanel
}

MainMenu.xib's File's Owner custom class should be switched to MYCustomWindowController from the application.

If MainMenu.xib has a window like in this example, it's "referencing outlet" needs to be connected to File's Owner->window.

If you started with a single view application, DELETE the App Delegate object from MainMenu.xib -- otherwise the xib will create a second instance of your app delegate. This can be terrible if you're referencing something like MYAppDelegate.managedObjectContext. If you need to bind to the application delegate, you can bind to the Application with a key path of delegate.managedObjectContext.

Why did I do this? Because sometimes my application launches with a GUI, and sometimes it doesn't.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...