Next Page > Hide TOC

NSDocumentController Class Reference

Inherits from
Conforms to
Framework
/System/Library/Frameworks/AppKit.framework
Availability
Available in Mac OS X v10.0 and later.
Companion guide
Declared in
NSDocumentController.h
Related sample code

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. NSDocumentController objects 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, the NSDocumentController management of the Open Recent menu is useful in applications that don’t use subclasses of NSDocument.

Adopted Protocols

NSCoding

Tasks

Obtaining the Shared Document Controller

Initializing a New NSDocumentController

Creating and Opening Documents

Managing Documents

Managing Document Types

Autosaving

Closing Documents

Responding to Action Messages

Managing the Open Panel

Managing the Open Recent Menu

Validating User Interface Items

Handling Errors

Deprecated Methods

Class Methods

sharedDocumentController

Returns the shared NSDocumentController instance.

+ (id)sharedDocumentController

Return Value

The shared NSDocumentController instance.

Discussion

If an NSDocumentController instance 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 NSWorkspaceWillPowerOffNotifications, and turns on the flag indicating that document user interfaces should be visible. You should always obtain your application’s NSDocumentController using this method.

Availability
See Also
Related Sample Code
Declared In
NSDocumentController.h

Instance Methods

addDocument:

Adds the given document to the list of open documents.

- (void)addDocument:(NSDocument *)document

Discussion

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

Availability
Related Sample Code
Declared In
NSDocumentController.h

autosavingDelay

Returns the time interval in seconds for periodic autosaving.

- (NSTimeInterval)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 autosaveDocumentWithDelegate:didAutosaveSelector:contextInfo: message. The default value is 0.

Availability
See Also
Declared In
NSDocumentController.h

clearRecentDocuments:

Empties the recent documents list for the application.

- (IBAction)clearRecentDocuments:(id)sender

Discussion

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

Availability
Declared In
NSDocumentController.h

closeAllDocumentsWithDelegate:didCloseAllSelector:contextInfo:

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

- (void)closeAllDocumentsWithDelegate:(id)delegate didCloseAllSelector:(SEL)didCloseAllSelector contextInfo:(void *)contextInfo

Discussion

Each NSDocument object is sent canCloseDocumentWithDelegate:shouldCloseSelector:contextInfo:, 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 YES if all documents are closed, and NO otherwise. Pass the contextInfo object with the callback. The didCloseAllSelector callback method should have the following signature:

- (void)documentController:(NSDocumentController *)docController  didCloseAll: (BOOL)didCloseAll contextInfo:(void *)contextInfo
Availability
Declared In
NSDocumentController.h

currentDirectory

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

- (NSString *)currentDirectory

Discussion

The first valid directory from the following list is returned:

Availability
See Also
Declared In
NSDocumentController.h

currentDocument

Returns the NSDocument object associated with the main window.

- (id)currentDocument

Discussion

This method returns nil 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];
Availability
See Also
Related Sample Code
Declared In
NSDocumentController.h

defaultType

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

- (NSString *)defaultType

Discussion

The default implementation of this method returns the first Editor type declared by the CFBundleDocumentTypes array in the application's Info.plist, or returns nil 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
Declared In
NSDocumentController.h

displayNameForType:

Returns the descriptive name for the specified document type, which is used in the File Format pop-up menu of the Save As dialog.

- (NSString *)displayNameForType:(NSString *)documentTypeName

Parameters
documentTypeName

The name of a document type, specified by CFBundleTypeName in the application’s Info.plist file.

Return Value

The descriptive name for the document type specified by documentTypeName. If there is no descriptive name, returns documentTypeName.

Discussion

For a document-based application, supported document types are specified in the Info.plist file by the CFBundleDocumentTypes array. Each document type is specified by a dictionary in this array, and is named by the CFBundleTypeName attribute. You can provide a descriptive, localized, representation of this name by providing a corresponding entry in the InfoPlist.strings file(s). For example, given an Info.plist file that contains the following fragment:

<dict>
    <key>CFBundleDocumentTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeName</key>
            <string>BinaryFile</string>
            <key>CFBundleTypeExtensions</key>
            <array>
                <string>binary</string>
            </array>

you could provide a descriptive name by adding an entry in the InfoPlist.strings file:

BinaryFile = "Binary file format";
Availability
See Also
Declared In
NSDocumentController.h

documentClassForType:

Returns the NSDocument subclass associated with a given document type.

- (Class)documentClassForType:(NSString *)documentTypeName

Parameters
documentTypeName

The name of a document type, specified by CFBundleTypeName in the application’s Info.plist file.

The document type must be one the receiver can read.

Return Value

Returns the NSDocument subclass associated with documentTypeName. If the class cannot be found, returns nil.

Discussion

Para

Availability
See Also
Declared In
NSDocumentController.h

documentClassNames

Returns the names of NSDocument subclasses supported by this application.

- (NSArray *)documentClassNames

Return Value

The names of NSDocument subclasses supported by this application.

Discussion

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

Availability
Declared In
NSDocumentController.h

documentForURL:

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

- (id)documentForURL:(NSURL *)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
Related Sample Code
Declared In
NSDocumentController.h

documentForWindow:

Returns the document object whose window controller owns a specified window.

- (id)documentForWindow:(NSWindow *)window

Return Value

The document object whose window controller owns window. Returns nil if window is nil, if window has no window controller, or if the window controller does not have an association with an instance of NSDocument.

Availability
See Also
Declared In
NSDocumentController.h

documents

Returns the NSDocument objects managed by the receiver.

- (NSArray *)documents

Return Value

The NSDocument objects managed by the receiver. If there are currently no documents, returns an empty NSArray object.

Availability
See Also
Related Sample Code
Declared In
NSDocumentController.h

hasEditedDocuments

Returns a Boolean value that indicates whether the receiver has any documents with unsaved changes.

- (BOOL)hasEditedDocuments

Return Value

YES if the receiver has any documents with unsaved changes, otherwise NO.

Availability
See Also
Declared In
NSDocumentController.h

init

This method is the designated initializer for NSDocumentController.

- (id)init

Discussion

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

Availability
Declared In
NSDocumentController.h

makeDocumentForURL:withContentsOfURL:ofType:error:

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.

- (id)makeDocumentForURL:(NSURL *)absoluteDocumentURL withContentsOfURL:(NSURL *)absoluteDocumentContentsURL ofType:(NSString *)typeName error:(NSError **)outError

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 nil after setting outError to point to an NSError object that encapsulates the reason why the document could not be instantiated. 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 initForURL:withContentsOfURL:ofType:error: message.

Availability
Declared In
NSDocumentController.h

makeDocumentWithContentsOfURL:ofType:error:

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

- (id)makeDocumentWithContentsOfURL:(NSURL *)absoluteURL ofType:(NSString *)typeName error:(NSError **)outError

Discussion

The URL is specified by absoluteURL and the document type by typeName. If not successful, the method returns nil after setting outError to point to an NSError that encapsulates the reason why the document could not be instantiated. 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 initWithContentsOfURL:ofType:error: message.

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

Availability
Related Sample Code
Declared In
NSDocumentController.h

makeUntitledDocumentOfType:error:

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

- (id)makeUntitledDocumentOfType:(NSString *)typeName error:(NSError **)outError

Discussion

The document type is specified by typeName. If not successful, the method returns nil after setting outError to point to an NSError object that encapsulates the reason why a new untitled document could not be instantiated. 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:error:.

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

Availability
Declared In
NSDocumentController.h

maximumRecentDocumentCount

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

- (NSUInteger)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
Declared In
NSDocumentController.h

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.

- (IBAction)newDocument:(id)sender

Discussion

It invokes openUntitledDocumentAndDisplay:error: 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.

Availability
See Also
Declared In
NSDocumentController.h

noteNewRecentDocument:

This method is called by NSDocument objects at appropriate times for managing the recent-documents list.

- (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.

Availability
Declared In
NSDocumentController.h

noteNewRecentDocumentURL:

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

- (void)noteNewRecentDocumentURL:(NSURL *)aURL

Discussion

NSDocument automatically calls this method when appropriate for NSDocument-based applications. Applications not based on NSDocument must also implement the application:openFile: 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).

Availability
Related Sample Code
Declared In
NSDocumentController.h

openDocument:

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.

- (IBAction)openDocument:(id)sender

Discussion

The method adds the newly created objects to the list of NSDocument objects managed by the receiver. This method invokes openDocumentWithContentsOfURL:display:error:, which actually creates the NSDocument objects.

Availability
See Also
Declared In
NSDocumentController.h

openDocumentWithContentsOfURL:display:error:

Opens a document located by the given URL presents its user interface if requested, and returns the document if successful.

- (id)openDocumentWithContentsOfURL:(NSURL *)absoluteURL display:(BOOL)displayDocument error:(NSError **)outError

Discussion

If not successful, the method returns nil after setting outError to point to an NSError object that encapsulates the reason why the document could not be opened.

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 makeDocumentWithContentsOfURL:ofType:error: to instantiate it, then invokes addDocument: to record its opening, and sends the document makeWindowControllers and showWindows messages if displayDocument is YES. If the document is already open it is just sent a showWindows message if displayDocument is YES.

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

Availability
Declared In
NSDocumentController.h

openUntitledDocumentAndDisplay:error:

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

- (id)openUntitledDocumentAndDisplay:(BOOL)displayDocument error:(NSError **)outError

Discussion

If not successful, the method returns nil after setting outError to point to an NSError that encapsulates the reason why a new untitled document could not be created.

The default implementation of this method invokes defaultType to determine the type of new document to create, invokes makeUntitledDocumentOfType:error: to create it, then invokes addDocument: to record its opening. If displayDocument is YES, 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:display: if it is overridden.

Availability
Related Sample Code
Declared In
NSDocumentController.h

presentError:

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

- (BOOL)presentError:(NSError *)error

Discussion

Returns YES if error recovery was done, NO otherwise. This method does not return until the user dismisses the alert and, if the error has recovery options and a recovery delegate, the error's recovery delegate is sent an attemptRecoveryFromError:optionIndex: message.

The default NSDocumentController 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. (The default NSDocument implementation of this method treats the shared NSDocumentController instance 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 subclasses an opportunity to customize error presentation. You should not override this method but should instead override willPresentError:.

Availability
See Also
Declared In
NSDocumentController.h

presentError:modalForWindow:delegate:didPresentSelector:contextInfo:

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

- (void)presentError:(NSError *)error modalForWindow:(NSWindow *)window delegate:(id)delegate didPresentSelector:(SEL)didPresentSelector contextInfo:(void *)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:

- (void)didPresentErrorWithRecovery:(BOOL)didRecover contextInfo:(void  *)contextInfo;

The default NSDocumentController 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. (The default NSDocument implementation of this method treats the shared NSDocumentController instance as the next responder and forwards these messages to it.)

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

Availability
See Also
Declared In
NSDocumentController.h

recentDocumentURLs

Returns the list of recent-document URLs.

- (NSArray *)recentDocumentURLs

Discussion

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

Availability
Declared In
NSDocumentController.h

removeDocument:

Removes the given document from the list of open documents.

- (void)removeDocument:(NSDocument *)document

Discussion

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

Availability
Related Sample Code
Declared In
NSDocumentController.h

reopenDocumentForURL:withContentsOfURL:error:

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

- (BOOL)reopenDocumentForURL:(NSURL *)absoluteDocumentURL withContentsOfURL:(NSURL *)absoluteDocumentContentsURL error:(NSError **)outError

Discussion

The document is located by absoluteDocumentURL and the contents are read from absoluteDocumentContentsURL. If not successful, the method returns NO after setting outError to point to an NSError object that encapsulates the reason why the document could not be reopened.

Availability
Declared In
NSDocumentController.h

reviewUnsavedDocumentsWithAlertTitle:cancellable:delegate:didReviewAllSelector:contextInfo:

Displays an alert dialog asking if the user wants to review unsaved documents (only if there are two or more unsaved documents), quit regardless of unsaved documents, or (if the choice is allowed) cancel the impending save operation.

- (void)reviewUnsavedDocumentsWithAlertTitle:(NSString *)title cancellable:(BOOL)cancellable delegate:(id)delegate didReviewAllSelector:(SEL)didReviewAllSelector contextInfo:(void *)contextInfo

Discussion

Assigns delegate to the panel. Invokes didReviewAllSelector with YES if quit without saving is chosen or if there are no dirty documents, and NO otherwise. If the user selects the “Review Unsaved” option, closeAllDocumentsWithDelegate:didCloseAllSelector:contextInfo: is invoked. This method is invoked when the user chooses the Quit menu command, and also when the computer power is being turned off. Note that title is ignored. Pass the contextInfo object with the callback.

The didReviewAllSelector callback method should have the following signature:

- (void)documentController:(NSDocumentController *)docController  didReviewAll: (BOOL)didReviewAll contextInfo:(void *)contextInfo
Availability
Declared In
NSDocumentController.h

runModalOpenPanel:forTypes:

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

- (NSInteger)runModalOpenPanel:(NSOpenPanel *)openPanel forTypes:(NSArray *)extensions

Discussion

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

Availability
Declared In
NSDocumentController.h

saveAllDocuments:

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

- (IBAction)saveAllDocuments:(id)sender

Availability
See Also
Declared In
NSDocumentController.h

setAutosavingDelay:

Sets the time interval in seconds for periodic autosaving.

- (void)setAutosavingDelay:(NSTimeInterval)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 autosaveDocumentWithDelegate:didAutosaveSelector:contextInfo: message. The default value is 0.

Availability
See Also
Declared In
NSDocumentController.h

typeForContentsOfURL:error:

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

- (NSString *)typeForContentsOfURL:(NSURL *)inAbsoluteURL error:(NSError **)outError

Discussion

The URL is represented by absoluteURL. If not successful, the method returns nil after setting outError to point to an NSError object that encapsulates the reason why the document type could not be determined, or the fact that the document type is unrecognized.

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

Availability
Declared In
NSDocumentController.h

URLsFromRunningOpenPanel

Creates an NSOpenPanel instance and initializes it appropriately.

- (NSArray *)URLsFromRunningOpenPanel

Discussion

This method uses runModalOpenPanel:forTypes: to run the open panel. Returns the chosen files as an array of URLs. Returns nil if the user cancels the Open panel or makes no selection.

Availability
Declared In
NSDocumentController.h

validateUserInterfaceItem:

Returns a Boolean value that indicates whether a given user interface item should be enabled.

- (BOOL)validateUserInterfaceItem:(id < NSValidatedUserInterfaceItem >)anItem

Parameters
anItem

The user interface item to validate. You can send anItem the action and tag messages.

Return Value

YES if anItem should be enabled, otherwise NO.

Discussion

Subclasses can override this method to perform additional validations. Subclasses should call super in their implementation for items they don’t handle themselves.

Availability
Declared In
NSDocumentController.h

willPresentError:

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

- (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
Declared In
NSDocumentController.h

Next Page > Hide TOC


© 2008 Apple Inc. All Rights Reserved. (Last updated: 2008-10-15)


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.