Next Page > Hide TOC

Legacy Documentclose button

Important: The information in this document is obsolete and should not be used for new development.

NSDocumentController

Inherits from
Implements
Package
com.apple.cocoa.application
Companion guide

Overview

An NSDocumentController object manages an application’s documents. As the first-responder target of New and Open menu commands, it creates and opens documents and tracks them throughout a session of the application. When opening documents, an NSDocumentController runs and manages the modal Open panel. NSDocumentControllers also maintain and manage the mappings of document types, extensions, and NSDocument subclasses as specified in the CFBundleDocumentTypes property loaded from the information property list (Info.plist).

You can use various NSDocumentController methods to get a list of the current documents; get the current document (which is the document whose window is currently key); get documents based on a given filename or window; and find out about a document’s extension, type, display name, and document class.

In some situations, it is worthwhile to subclass NSDocumentController in non-NSDocument-based applications to get some of its features. For example, NSDocumentController’s management of the Open Recent menu is useful in applications that don’t use subclasses of NSDocument.

Tasks

Constructors

Obtaining the Shared Document Controller

Creating and Opening Documents

Handling Errors

Managing the Open Panel

Autosaving

Responding to Action Messages

Managing Documents

Managing the Open Recent Menu

Managing Document Types

Validating User Interface Items

Deprecated Methods

Constructors

NSDocumentController

Creates a new NSDocumentController.

public NSDocumentController()

Discussion

The first instance of NSDocumentController or any of its subclasses becomes the shared instance.

Static Methods

sharedDocumentController

Returns the shared NSDocumentController instance.

public static NSDocumentController sharedDocumentController()

Discussion

If one doesn’t exist yet, it is created. Initialization reads in the document types from the CFBundleDocumentTypes property list (in Info.plist), registers the instance for WorkspaceWillPowerOffNotifications, and turns on the flag indicating that document user interfaces should be visible. You should always obtain your application’s NSDocumentController using this method.

See Also

Instance Methods

addDocument

Adds document to the list of open documents.

public void addDocument(NSDocument document)

Discussion

The open... methods automatically call addDocument. This method is mostly provided for subclassers that want to know when documents arrive.

autosavingDelay

Returns the time interval in seconds for periodic autosaving.

public double autosavingDelay()

Discussion

A value of 0 indicates that periodic autosaving should not be done at all. NSDocumentController uses this number as the amount of time to wait between detecting that a document has unautosaved changes and sending the document an autosaveDocument message. The default value is 0.

Availability
See Also

clearRecentDocuments

Empties the recent documents list for the application.

public void clearRecentDocuments(Object sender)

Discussion

This is the action for the Clear menu command, but it can be invoked directly if necessary.

closeAllDocuments

Attempts to close all documents owned by the receiver and returns whether all documents were closed.

public boolean closeAllDocuments()

Discussion

It does not ask users whether they want to save documents. This method is invoked in reviewUnsavedDocumentsWithAlertTitle when users decide to discard all changes.

Iterates through all the open documents and tries to close them one by one using delegate.

public void closeAllDocuments(Object delegate, NSSelector didCloseAllSelector, Object contextInfo)

Discussion

Each NSDocument is sent canCloseDocument, which, if the document is dirty, gives it a chance to refuse to close or to save itself first. This method may ask whether to save or to perform a save.

The didCloseAllSelector callback method is invoked with true if all documents are closed, and false otherwise. Pass contextInfo with the callback. The didCloseAllSelector callback method should have the following signature:

public void documentControllerDidCloseAll (NSDocumentController  docController, boolean  didCloseAll, Object contextInfo)

currentDirectory

Returns the directory path to be used as the starting point in the Open panel.

public String currentDirectory()

Discussion

The first valid directory from the following list is returned:

See Also

currentDocument

Returns the NSDocument object associated with the main window.

public NSDocument currentDocument()

Discussion

This method returns null if it is called when its application is not active. This can occur during processing of a drag-and-drop operation, for example, in an implementation of readSelectionFromPasteboard:. In such a case, send the following message instead from an NSView subclass associated with the document:

[[[self window] windowController] document];
See Also

defaultType

Returns the name of the document type that should be used when creating new documents.

public String defaultType()

Discussion

The default implementation of this method returns the first Editor type declared in the application's Info.plist, or returns null if no Editor type is declared. You can override it to customize the type of document that is created when, for instance, the user chooses New in the File menu.

Availability

displayNameForType

Returns the descriptive name for the document type (documentTypeName), which is often part of the document’s window title.

public String displayNameForType(String documentTypeName)

Discussion

This returned value is associated with the TypeName key in the CFBundleDocumentTypes property list. If there is no such value, documentTypeName is returned.

See Also

documentClassForType

Returns the NSDocument subclass associated with document type documentTypeName.

public Class documentClassForType(String documentTypeName)

Discussion

The document type must be one the document can read. If the class cannot be found, returns null.

See Also

documentClassNames

Returns the names of NSDocument subclasses supported by this application.

public NSArray documentClassNames()

Discussion

The default implementation of this method returns information derived from the application's Info.plist. You can override it to return the names of document classes that are dynamically loaded from plugins.

Availability

documentForFileName

This method has been deprecated.

public NSDocument documentForFileName(String fileName)

Discussion

Returns the NSDocument object for the file in which the document data is stored. The fileName argument is a fully qualified path in the file system. Returns null if no document can be found.

Availability
See Also

documentForURL

Returns, for a given URL, the open document whose file or file package is located by the URL, or null if there is no such open document.

public NSDocument documentForURL(URL absoluteURL)

Discussion

The default implementation of this method queries each open document to find one whose URL matches, and returns the first one whose URL does match.

For backward binary compatibility with Mac OS X v10.3 and earlier, the default implementation of this method instead invokes documentForFileName if it is overridden and the URL uses the file: scheme.

Availability

documentForWindow

Returns the NSDocument object whose window controller owns window.

public NSDocument documentForWindow(NSWindow window)

Discussion

Returns null if window is null, if window has no window controller, or if the window controller does not have an association with an NSDocument.

See Also

documents

Returns the NSDocument objects managed by the receiver.

public NSArray documents()

Discussion

If there are currently no documents, returns an empty NSArray.

See Also

fileExtensionsFromType

Returns the allowable file extensions (as String objects) for document type documentTypeName.

public NSArray fileExtensionsFromType(String documentTypeName)

Discussion

The first string in the returned NSArray is typically the most common extension. The array may also contain encoded HFS file types as will as filename extensions.

See Also

fileNamesFromRunningOpenPanel

This method has been deprecated.

public NSArray fileNamesFromRunningOpenPanel()

Discussion

Returns a selection of files chosen by the user in the Open panel. Each file in the returned NSArray is a fully qualified path to the file’s location in the file system. This method is invoked by openDocument, and it invokes runModalOpenPanel after initializing the Open panel (which includes getting the starting directory with currentDirectory). Returns null if the user cancels the Open panel or makes no selection.

Availability

hasEditedDocuments

Returns whether the receiver has any documents with unsaved changes.

public boolean hasEditedDocuments()

See Also

lastError

Returns the NSError object that was most recently set.

public NSError lastError()

Discussion

Errors are set by NSDocument Java member functions or overrides using the setLastError member function. Typically, this member function is called only by the Application Kit itself.

Availability
See Also

makeDocumentForURLWithContentsOfURLOfType

Instantiates a document located by a URL, of a specified type, but by reading the contents for the document from another URL, and returns it if successful.

public NSDocument makeDocumentForURLWithContentsOfURLOfType(URL absoluteDocumentURL, URL absoluteDocumentContentsURL, String typeName)

Discussion

The URL is specified by absoluteDocumentURL, the type by typeName, and the other URL providing the contents by absoluteDocumentContentsURL. If not successful, the method returns null. The default implementation of this method invokes documentClassForType to find out the class of document to instantiate, allocates a document object, and initializes it by sending it an initForURLWithContentsOfURLOfType message.

Availability

makeDocumentWithContentsOfFile

This method has been deprecated.

public NSDocument makeDocumentWithContentsOfFile(String fileName, String docType)

Discussion

Creates and returns an NSDocument object for document type docType from the contents of the file fileName, which must be a fully qualified path. Returns null if the NSDocument subclass for docType couldn’t be determined or if the object couldn’t be created. This method is invoked by openDocumentWithContentsOfFile.

Availability
See Also

makeDocumentWithContentsOfURL

public NSDocument makeDocumentWithContentsOfURL(java.net.URL aURL, String docType)

Discussion

Creates and returns an NSDocument object for document type docType from the contents of aURL. Returns null if the NSDocument subclass for docType couldn’t be determined or if the object couldn’t be created. This method is invoked by openDocumentWithContentsOfURL.

See Also

makeDocumentWithContentsOfURLOfType

Instantiates a document located by a URL, of a specified type, and return it if successful.

public NSDocument makeDocumentWithContentsOfURLOfType(URL absoluteURL, String typeName)

Discussion

The URL is specifed by absoluteURL and the document type by typeName. If not successful, the method returns null. The default implementation of this method invokes documentClassForType to find out the class of document to instantiate, allocates a document object, and initializes it by sending it an initWithContentsOfURLOfType message.

For backward binary compatibility with Mac OS X v10.3 and earlier, the default implementation of this method instead invokes makeDocumentWithContentsOfFile if it is overridden and the URL uses the file: scheme.

Availability

makeUntitledDocumentOfType

Instantiates a new untitled document of the specified type and returns it if successful.

public NSDocument makeUntitledDocumentOfType(String typeName)

Discussion

The document type is specified by typeName. If not successful, the method returns null. The default implementation of this method invokes documentClassForType to find out the class of document to instantiate, then allocates and initializes a document by sending it initWithType.

Availability

maximumRecentDocumentCount

Returns the maximum number of items that may be presented in the standard Open Recent menu.

public int maximumRecentDocumentCount()

Discussion

A value of 0 indicates that NSDocumentController will not attempt to add an Open Recent menu to your application's File menu, although NSDocumentController will not attempt to remove any preexisting Open Recent menu item. The default implementation returns a value that is subject to change and may or may not be derived from a setting made by the user in System Preferences.

Availability

newDocument

An action method invoked by the New menu command, this method creates a new NSDocument object and adds it to the list of such objects managed by the receiver.

public void newDocument(Object sender)

Discussion

It invokes openUntitledDocumentOfType with the document type (first argument) being the first one specified in the CFBundleDocumentTypes property (defined in Info.plist); the document type determines the NSDocument subclass used to instantiate the document object.

See Also

noteNewRecentDocument

This method is called by NSDocuments at appropriate times for managing the recents list.

public void noteNewRecentDocument(NSDocument aDocument)

Discussion

This method constructs a URL and calls noteNewRecentDocumentURL. Subclasses might override this method to prevent certain documents or kinds of documents from getting into the list.

noteNewRecentDocumentURL

This method should be called by applications not based on NSDocument when they open or save documents identified by aURL.

public void noteNewRecentDocumentURL(java.net.URL aURL)

Discussion

NSDocument automatically calls this method when appropriate for NSDocument-based applications. Applications not based on NSDocument must also implement the applicationOpenFile method in the application delegate to handle requests from the Open Recent menu command. You can override this method in an NSDocument-based application to prevent certain kinds of documents from getting into the list (but you have to identify them by URL).

openDocument

public void openDocument(Object sender)

Discussion

An action method invoked by the Open menu command, it runs the modal Open panel and, based on the selected filenames, creates one or more NSDocument objects from the contents of the files; it adds these objects to the list of NSDocument objects managed by the receiver. This method invokes openDocumentWithContentsOfFile, which actually creates the NSDocument objects.

See Also

openDocumentWithContentsOfFile

This method has been deprecated.

public NSDocument openDocumentWithContentsOfFile(String fileName, boolean flag)

Discussion

Returns an NSDocument object created from the contents of the file fileName (an absolute path) and displays it if flag is true. The returned object is added to the receiver’s list of managed documents. Returns null if the object could not be created, typically because fileName does not point to a valid file or because there is no NSDocument subclass for the document type (as indicated by the file extension or HFS file type). Even if flag is true, the document is not displayed if shouldCreateUI returns false. This method invokes makeDocumentWithContentsOfFile to obtain the created NSDocument object. If you override this method, your implementation should be prepared to handle either true or false.

To handle an Open Documents Apple event, the Application Kit’s built-in Apple event handling automatically invokes this method with the path to the file to open and a display argument.

Invoked with a display argument of true instead of false when a Print Documents Apple event is handled. This may have been handled differently in versions of Mac OS X prior to version 10.3.

Availability
See Also

openDocumentWithContentsOfURL

Opens a document located by a URL absoluteURL, presents its user interface if displayDocuments is true, and returns the document if successful.

public NSDocument openDocumentWithContentsOfURL(URL absoluteURL, boolean displayDocument)

Discussion

If not successful, the method returns null.

The default implementation of this method checks to see if the document is already open according to documentForURL, and if it is not open determines the type of the document, invokes makeDocumentWithContentsOfURLOfType to instantiate it, then invokes addDocument to record its opening, and sends the document makeWindowControllers and showWindows messages if displayDocument is true. If the document is already open it is just sent a showWindows message if displayDocument is true.

For backward binary compatibility with Mac OS X v10.3 and earlier, the default implementation of this method instead invokes openDocumentWithContentsOfFile, if it is overridden and the URL uses the file: scheme.

openUntitledDocument

Creates a new untitled document, presents its user interface if displayDocument is true, and returns the document if successful.

public NSDocument openUntitledDocument(boolean displayDocument)

Discussion

If not successful, the method returns null.

The default implementation of this method invokes defaultType to determine the type of new document to create, invokes makeUntitledDocumentOfType to create it, then invokes addDocument to record its opening. If displayDocument is true, it then sends the new document makeWindowControllers and showWindows messages.

For backward binary compatibility with Mac OS X v10.3 and earlier, the default implementation of this method instead invokes openUntitledDocumentOfType if it is overridden.

Availability

openUntitledDocumentOfType

public NSDocument openUntitledDocumentOfType(String docType, boolean display)

Discussion

Returns an NSDocument object instantiated from the NSDocument subclass required by document type docType and displays it if flag is true. The returned object is added to the receiver’s list of managed documents. Returns null if the object could not be created, typically because no NSDocument subclass could be found for docType. Even if flag is true, the document is not displayed if shouldCreateUI returns false.

See Also

presentError

Presents an error alert to the user as a modal panel.

public boolean presentError(NSError error)

Discussion

Returns true if error recovery was done, false otherwise. This method does not return until the user dismisses the alert.

NSDocumentController's default implementation of this method is equivalent to that of NSResponder while treating the application object as the next responder and forwarding error presentation messages to it. (NSDocument’s default implementation of this method treats the shared NSDocumentController as the next responder and forwards these messages to it.) The default implementations of several NSDocumentController methods invoke this method.

The default implementation of this method invokes willPresentError to give subclassers an opportunity to customize error presentation. You should not override this method but should instead override willPresentError.

Availability
See Also

presentErrorModalForWindow

Presents an error alert to the user as a modal panel.

public void presentErrorModalForWindow(NSError error, NSWindow window, Object delegate, NSSelector didPresentSelector, Object contextInfo)

Discussion

When the user dismisses the alert and any recovery possible for the error and chosen by the user has been attempted, sends the message didPresentSelector to the specified delegate. The method selected by didPresentSelector must have the same signature as:

public void didPresentErrorWithRecovery (boolean didRecover, Object  contextInfo)

NSDocumentController's default implementation of this method is equivalent to that of NSResponder while treating the application object as the next responder and forwarding error presentation messages to it. (NSDocument’s default implementation of this method treats the shared NSDocumentController as the next responder and forwards these messages to it.)

The default implementation of this method invokes willPresentError to give subclassers an opportunity to customize error presentation. You should not override this method but should instead override willPresentError.

Availability
See Also

recentDocumentURLs

Returns the list of recent document URLs.

public NSArray recentDocumentURLs()

Discussion

This method is not a good one to override since the internals of NSDocumentController do not generally use it.

removeDocument

Removes document from the list of open documents.

public void removeDocument(NSDocument document)

Discussion

A document will automatically call removeDocument when it closes. This method is mostly provided for subclassers that want to know when documents close.

reopenDocumentForURLWithContentsOfURL

Reopens an autosaved document located by a URL, by reading the contents for the document from another URL, presents its user interface, and returns true if successful.

public boolean reopenDocumentForURLWithContentsOfURL(URL absoluteDocumentURL, URL absoluteDocumentContentsURL)

Discussion

The document is located by absoluteDocumentURL and the contents are read from absoluteDocumentContentsURL. If not successful, the method returns false.

Availability

reviewUnsavedDocumentsWithAlertTitle

This method variant has been deprecated. Instead use the other variant of this method.

public boolean reviewUnsavedDocumentsWithAlertTitle(String title, boolean flag)

Discussion

Displays an alert dialog asking users if they want to review unsaved documents, quit regardless of unsaved documents, or (if flag is true) cancel the impending save-and-terminate operation. Returns true if the application is to quit and false if otherwise (used only when the application is terminating). If the user selects the Review Unsaved option, closeAllDocuments is invoked. This method is invoked when users choose the Quit menu command and when the computer power is being turned off (in which case, flag is false).

Displays an alert dialog asking if the user wants to review unsaved documents, quit regardless of unsaved documents, or (if cancellable is true) cancel the impending save operation.

public void reviewUnsavedDocumentsWithAlertTitle(String title, boolean cancellable, Object delegate, NSSelector didReviewAllSelector, Object contextInfo)

Discussion

Invokes didReviewAllSelector with true if quit without saving is chosen or if there are no dirty documents, and false otherwise. Assigns delegate to the panel. If the user selects the “Review Unsaved” option, closeAllDocuments is invoked. This method is invoked when the user chooses the Quit menu command and also when the computer power is being turned off (in which case, cancellable is false). Note that title is ignored. Pass the contextInfo object with the callback.

The didReviewAllSelector callback method should have the following signature:

public void documentControllerDidReviewAll (NSDocumentController  docController, boolean  didReviewAll, Object contextInfo)

runModalOpenPanel

Invokes NSOpenPanel’s runModalForTypes, passing the openPanel object and the file extensions associated with a document type.

public int runModalOpenPanel(NSOpenPanel openPanel, NSArray extensions)

Discussion

This method is invoked by the fileNamesFromRunningOpenPanel method. extensions may also contain encoded HFS file types as well as filename extensions.

saveAllDocuments

As the action method invoked by the Save All command, saves all open documents of the application that need to be saved.

public void saveAllDocuments(Object sender)

See Also

setAutosavingDelay

Sets the time interval in seconds for periodic autosaving.

public void setAutosavingDelay(double autosavingDelay)

Discussion

A value of 0 indicates that periodic autosaving should not be done at all. NSDocumentController uses this number as the amount of time to wait between detecting that a document has unautosaved changes and sending the document an autosaveDocument message. The default value is 0.

Availability
See Also

setLastError

Sets the NSError object that will be returned by the lastError member function.

public void setLastError(NSError inError)

Discussion

The inError parameter represents the NSError object to be set.

Whenever your application’s override of an NSDocumentController member function detects failure and is going to return null or whatever signals failure for that particular function, it should first call this function and pass in an NSError object that encapsulates the reason for the failure. However, it needn’t do so if it’s going to signal failure because it called a member function that itself failed and is expected to have already called setLastError.

Availability
See Also

setShouldCreateUI

This method has been deprecated.

public void setShouldCreateUI(boolean flag)

Discussion

Sets whether the window controllers (NSWindowControllers) of a document should be created when the document is created. When a window controller is created, it loads the nib file containing the window it manages. Often flag is set to false for scripting or searching operations involving the document’s data.

Availability
See Also

shouldCreateUI

This method has been deprecated.

public boolean shouldCreateUI()

Discussion

Returns whether the window controllers (NSWindowControllers) of a document should be created when the document is created.

Availability
See Also

typeForContentsOfURL

Returns, for a specified URL, the name of the document type that should be used when opening the document at that location, if successful.

public String typeForContentsOfURL(URL absoluteURL)

Discussion

The URL is represented by absoluteURL. If not successful, the method returns null.

You can override this method to customize type determination for documents being opened.

Availability

typeFromFileExtension

Returns the document type associated with files having extension fileExtensionOrHFSFileType.

public String typeFromFileExtension(String fileExtensionOrHFSFileType)

Discussion

fileExtensionOrHFSFileType may also be an encoded HFS file type, as well as a filename extension.

See Also

URLsFromRunningOpenPanel

Creates an NSOpenPanel and initializes it appropriately.

public NSArray URLsFromRunningOpenPanel()

Discussion

Then uses runModalOpenPanel to run the NSOpenPanel. Returns the chosen files as an array of URLs. Returns null if the user cancels the Open panel or makes no selection.

validateMenuItem

Validates menu item anItem, returning true if it should be enabled, false otherwise.

public boolean validateMenuItem(NSMenuItem anItem)

Discussion

As implemented, if anItem is the Save All menu item, returns true if there are any edited documents. Subclasses can override this method to perform additional validations. Subclasses should call super in their implementation for items they don’t handle themselves.

willPresentError

Called when the receiver is about to present an error, returns the error that should actually be presented.

public NSError willPresentError(NSError error)

Discussion

The default implementation of this method merely returns the passed-in error. The returned error may simply be forwarded to the application object.

You can override this method to customize the presentation of errors by examining the passed-in error and, for example, returning more specific information. When you override this method always check the NSError object's domain and code to discriminate between errors whose presentation you want to customize and those you don't. For errors you don't want to customize, call the superclass implementation, passing the original error.

Availability
See Also


Next Page > Hide TOC


© 1997, 2007 Apple Inc. All Rights Reserved. (Last updated: 2007-02-01)


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.