-->

How to Create a Document-Based OS X App that Launc

2020-07-24 04:21发布

问题:

I am used to developing non-document-based applications with a single window, but now I am working on a document based application that I created using the document-based template in Xcode 5. When I run my application, it opens a new untitled document upon launch. Instead of automatically creating a new document, I would like my application to display an "Open..." dialog much like Xcode, TextEdit, and other Apple apps do. How do I go about implementing this? Is there a flag somewhere that I can set to show the dialog instead of a new document, or do I have to create an application delegate that shows the dialog upon launch? Thanks for your advice.

回答1:

That would be customized behaviour.

In your application controller override applicationShouldOpenUntitledFile: to prevent opening a blank document at startup, then display the file dialog.



回答2:

This is not hard but not obvious and takes a few steps to get going.

Add a window to your MainMenu.xib Set the Visible at launch to NO in the inspector. Now create an NSObject subclass in your project. You might include AppDelegate in the name because you will want to make it the delegate of your app. In the interface header be sure to declare the protocol right after the word NSObject. While there, add an IBOutlet property an NSWindow. Back to the MainMenu.xib ... Add an NSObject (blue cube) to your xib from the library and set its class to your new app delegate class. Next connect your window to the property in your app delegate class and connect the window's delegate outlet to your app delegate.

Now the menu. Locate the View menu in MainMenu and add one NSMenuItem. Give it a title. "My fancy main window" or whatever. Now connect it to your app delegate with both an IBOutlet (in case you want to fiddle with its enabled state or title later ) And add an IBAction for this menu item as well. Something like showMyFancyWindow:

This menu item will be persistent. In your IBAction method call makeKeyAndOrderFront: with your app delegate's property for your window as the argument.

Extra credit

Add a BOOL property to your app delegate. Something like showsMyFancyWindowAtLaunch

Create a constant NSString as a key above your @implementation line. Add a checkbox button to your window. Bind its value to your BOOL. Add an IBAction method for the checkbox. Inside that [[NSUserDefaults sharedDefaults] setBool: self.showsMyFancyWindowAtLaunch forKey: theConstStringKeyYouCreated]

Then in your applicationDidFinishLaunching: Use the corresponding bool:forKey: method of NSUserDefaults to check whether or not to call showMyFancyWindow: method at launch.