NSDocumentController Class Reference

Inherits from
Conforms to
Framework
/System/Library/Frameworks/AppKit.framework
Availability
Available in 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 Dialog

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
  • Available in OS X v10.0 and later.
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
  • Available in OS X v10.0 and later.
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
  • Available in OS X v10.4 and later.
Declared In
NSDocumentController.h

beginOpenPanel:forTypes:completionHandler:

Presents a nonmodal Open dialog that displays files that can be opened based on a list of UTIs.

- (void)beginOpenPanel:(NSOpenPanel *)openPanel forTypes:(NSArray *)inTypes completionHandler:(void (^)(NSInteger result))completionHandler
Parameters
openPanel

The open panel to present.

inTypes

A list of file types that the user should be allowed to choose in the open panel.

completionHandler

The completion handler that runs when the user clicks the OK or Cancel button in the open panel.

The block takes the following parameter:

result

Either NSOKButton or NSCancelButton, depending on which button the user pressed to dismiss the dialog.

Discussion

This method is called by openDocument: and beginOpenPanelWithCompletionHandler: to do the actual work. You typically do not call this method directly. You can override this method as needed to customize the Open panel or to alter the list of UTIs in the inTypes parameter.

You can also override this method if you to perform additional cleanup (for example, if you customized the open panel and need to tear down an accessory view). Your overridden implementation should call the underlying method on super, passing a custom completion handler. That handler should do the additional cleanup work, and then should call the completion handler block that was provided by the caller.

Availability
  • Available in OS X v10.8 and later.
Related Sample Code
Declared In
NSDocumentController.h

beginOpenPanelWithCompletionHandler:

Presents an Open dialog and delivers the results to a completion handler as an array of URLs for the chosen files (or nil).

- (void)beginOpenPanelWithCompletionHandler:(void (^)(NSArray *))completionHandler
Parameters
completionHandler

The completion handler that is called when the user clicks the OK or Cancel button in the open panel.

Discussion

This method presents either a modal or nonmodal open panel, depending on which methods are overridden. Although you can call this method in other circumstances, this method is most commonly called by openDocument: in response to the user choosing Open… from the File menu.

If you override openDocument:, you should typically call this method instead of calling beginOpenPanel:forTypes:completionHandler: or URLsFromRunningOpenPanel directly, because this method runs the modal panel in a way that is backwards compatible with subclasses that override runModalOpenPanel:forTypes: without overriding beginOpenPanel:forTypes:completionHandler:. Also, its completion handler determines which button the user pressed (to determine whether to return the array or nil) and orders out the open panel.

You can override this method to change the open panel presentation (adding an accessory view, for example) or change the UTI array that limits which files are selectable.

The default implementation of this method calls either URLsFromRunningOpenPanel to run a modal open panel or beginOpenPanel:forTypes:completionHandler: to begin a nonmodal open panel. If the user chooses to open files, the default implementation calls the completion handler with a nil array parameter. If the user cancels the Open dialog, the default implementation calls the completion handler with a nil array parameter.

If you override this method, your method should typically call the underlying method on super because of the additional code that it provides for free. Specifically, this method runs the modal panel in a way that is backwards compatible with subclasses that override runModalOpenPanel:forTypes: without overriding beginOpenPanel:forTypes:completionHandler:. Also, its completion handler determines which button the user pressed (to determine whether to return the array or nil) and orders out the open panel.

Availability
  • Available in OS X v10.8 and later.
Declared In
NSDocumentController.h

clearRecentDocuments:

Empties the recent documents list for the application.

- (void)clearRecentDocuments:(id)sender
Discussion

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

Availability
  • Available in OS X v10.0 and later.
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 called 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
  • Available in OS X v10.0 and later.
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:

  • The directory location where the current document was last saved

  • The last directory visited in the Open panel

  • The user’s home directory

Availability
  • Available in OS X v10.0 and later.
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
  • Available in OS X v10.0 and later.
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
  • Available in OS X v10.4 and later.
Related Sample Code
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
  • Available in OS X v10.0 and later.
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.

Availability
  • Available in OS X v10.0 and later.
Related Sample Code
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
  • Available in OS X v10.4 and later.
Related Sample Code
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
Parameters
absoluteURL

The URL of the document you wish to look up.

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.

Availability
  • Available in OS X v10.4 and later.
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
  • Available in OS X v10.0 and later.
Related Sample Code
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
  • Available in OS X v10.0 and later.
Related Sample Code
Declared In
NSDocumentController.h

duplicateDocumentWithContentsOfURL:copying:displayName:error:

Creates a new document by reading the contents for the document from another URL, presents its user interface, and returns the document if successful.

- (NSDocument *)duplicateDocumentWithContentsOfURL:(NSURL *)url copying:(BOOL)duplicateByCopying displayName:(NSString *)displayNameOrNil error:(NSError **)outError
Parameters
url

The URL locating the document from which contents of the new document are copied.

duplicateByCopying

If YES, the contents located at the passed-in URL are copied into a file located in the directory used for the autosaved contents of untitled documents.

displayNameOrNil

If not nil then this value is used to derive a display name for the new document that does not match one that is already in use by an open document.

outError

On return, if duplication is unsuccessful, a pointer to an error object that encapsulates the reason the document could not be created.

Return Value

The newly created NSDocument object, or, if the document could not be created, nil.

Discussion

The default implementation of this method copies the file if specified, determines the type of the document, calls makeDocumentForURL:withContentsOfURL:ofType:error: to instantiate it, sends the document setDisplayName: to name it if displayNameOrNil is not nil, calls addDocument: to record its opening, and sends the document makeWindowControllers and showWindows messages.

The default implementation of this method uses the file coordination mechanism introduced in OS X v10.7. It passes the document to the NSFileCoordinator method addFilePresenter: immediately after calling the addDocument: method. (The balancing invocation of the NSFileCoordinator method removeFilePresenter: is in the NSDocument method close.)

You can override this method to customize how documents are duplicated. It is called by the NSDocument method duplicateAndReturnError:. It may also be called from other places in AppKit.

In most cases, an app does not need to call this method directly.

Availability
  • Available in OS X v10.7 and later.
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
  • Available in OS X v10.0 and later.
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
  • Available in OS X v10.0 and later.
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 calls 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
  • Available in OS X v10.4 and later.
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 calls 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.

Availability
  • Available in OS X v10.4 and later.
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 calls documentClassForType: to find out the class of document to instantiate, then allocates and initializes a document by sending it initWithType:error:.

Availability
  • Available in OS X v10.4 and later.
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
  • Available in OS X v10.4 and later.
Declared In
NSDocumentController.h

newDocument:

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

- (void)newDocument:(id)sender
Discussion

This method calls openUntitledDocumentAndDisplay:error:.

Availability
  • Available in OS X v10.0 and later.
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
  • Available in OS X v10.0 and later.
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
  • Available in OS X v10.0 and later.
Declared In
NSDocumentController.h

openDocument:

An action method called 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.

- (void)openDocument:(id)sender
Discussion

The method adds the newly created objects to the list of NSDocument objects managed by the document controller. This method calls openDocumentWithContentsOfURL:display:completionHandler:, which actually creates the NSDocument objects.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocumentController.h

openDocumentWithContentsOfURL:display:completionHandler:

Opens a document located by a URL, optionally presents its user interface, and calls the passed-in completion handler.

- (void)openDocumentWithContentsOfURL:(NSURL *)url display:(BOOL)displayDocument completionHandler:(void (^)(NSDocument *document, BOOL documentWasAlreadyOpen, NSError *error))completionHandler
Parameters
url

The URL locating the document to open.

displayDocument

If YES, displays the document’s user interface.

completionHandler

The completion handler block object passed in to be called at some point in the future, perhaps after the method invocation has returned. The completion handler must be called on the main thread.

The block takes three arguments:

document

The document that was opened, if successful. Otherwise, nil.

documentWasAlreadyOpen

Whether the document was already open or being opened when this method was called.

error

If not successful, an NSError object that encapsulates the reason why the document could not be opened.

Discussion

The default implementation of this method checks to see if the document is already open or being opened, and if it is not determines the type of the document, calls makeDocumentWithContentsOfURL:ofType:error: to instantiate it, and calls addDocument: to record its opening. If displayDocument is YES and the document is not already open, the default implementation calls makeWindowControllers and showWindows. If the document is already open, the implementation just calls showWindows if displayDocument is YES. If the relevant document class returns YES when sent canConcurrentlyReadDocumentsOfType: then the invocation of makeDocumentWithContentsOfURL:ofType:error: is done on a thread other than the main one, and when that has returned, the rest of the operation is done on the main thread.

The default implementation of this method uses the file coordination mechanism that was added to the Foundation framework in OS X v10.7. All of the work it does is one big coordinated read, and it passes the document to the NSFileCoordinator method addFilePresenter: right after calling addDocument:. (The balancing invocation of the NSFileCoordinator method removeFilePresenter: is in the NSDocument method close.)

You can override this method to customize how documents are opened. Its implementation, however, is somewhat complex, so you should generally investigate overriding one of the methods that it calls instead. However, you can override this method to do additional work before calling the underlying method on super. You can also call the underlying method on super with a custom completion handler that performs additional work before calling the original completion handler. If you do override this method you should investigate whether you should also override reopenDocumentForURL:withContentsOfURL:display:completionHandler: to apply the same customization. In either case, take care to always call the completion handler on the main thread.

You can call this method to open a document.

Special Considerations

For backward binary compatibility with OS X v10.6 and earlier, the default implementation of this method calls [self openDocumentWithContentsOfURL:url display:displayDocument error:&anError] if that method or the even older openDocumentWithContentsOfFile:display: method is overridden and this one is not, instead of calling makeDocumentWithContentsOfURL:ofType:error: and all the rest.

Availability
  • Available in OS X v10.7 and later.
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
Parameters
displayDocument

YES if the user interface for the document should be shown, otherwise NO.

outError

On return, an error if the document could not be created, otherwise nil.

Return Value

Returns the new document object, or nil if a new untitled document could not be created. If this method returns nil, it also sets the address referenced by outError to an NSError object that tell why the document could not be created.

Discussion

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

Availability
  • Available in OS X v10.4 and later.
Related Sample Code
Declared In
NSDocumentController.h

presentError:

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

- (BOOL)presentError:(NSError *)error
Parameters
error

An object containing the error that should be presented.

Return Value

Returns YES if error recovery was done, NO otherwise.

Discussion

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 call this method.

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

Availability
  • Available in OS X v10.4 and later.
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 calls willPresentError: to give subclasses an opportunity to customize error presentation. You should not override this method but should instead override willPresentError:.

Availability
  • Available in OS X v10.4 and later.
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
  • Available in OS X v10.0 and later.
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
  • Available in OS X v10.0 and later.
Related Sample Code
Declared In
NSDocumentController.h

reopenDocumentForURL:withContentsOfURL:display:completionHandler:

Reopens a document, optionally located by a URL, by reading the contents for the document from another URL, optionally presents its user interface, and calls the passed-in completion handler.

- (void)reopenDocumentForURL:(NSURL *)urlOrNil withContentsOfURL:(NSURL *)contentsURL display:(BOOL)displayDocument completionHandler:(void (^)(NSDocument *document, BOOL documentWasAlreadyOpen, NSError *error))completionHandler
Parameters
urlOrNil

The URL locating the reopened document, unless nil. A nil parameter value indicates that the reopened document is to have no fileURL, like an untitled document.

contentsURL

The URL (which may or may not be different from the URL of the reopened document) of the document from which the contents are read.

displayDocument

If YES, displays the document’s user interface.

completionHandler

The completion handler block object passed in to be called at some point in the future, perhaps after the method invocation has returned. The completion handler must be called on the main thread.

The block takes three arguments:

document

The document that was opened, if successful. Otherwise, nil.

documentWasAlreadyOpen

Whether the document was already open or being opened when this method was called.

error

If not successful, an NSError object that encapsulates the reason why the document could not be opened.

Discussion

The default implementation of this method is very similar to openDocumentWithContentsOfURL:display:completionHandler:, the primary difference being that it calls makeDocumentForURL:withContentsOfURL:ofType:error: instead of makeDocumentWithContentsOfURL:ofType:error:.

You can override this method to customize how documents are reopened during application launching by the restorable state mechanism introduced in OS X v10.7. Its implementation, however, is somewhat complex, so you should generally investigate overriding one of the methods that it calls instead. However, you can override this method to do additional work before calling the underlying method on super. You can also call the underlying method on super with a custom completion handler that performs additional work before calling the original completion handler.

Applications probably do not need to call this method directly.

For backward binary compatibility with OS X v10.6 and earlier, the default implementation of this method calls [self reopenDocumentForURL:url withContentsOfURL:contentsURL error:&anError] if that method is overridden and this one is not, instead of calling makeDocumentForURL:withContentsOfURL:ofType:error: and all the rest.

Availability
  • Available in OS X v10.7 and later.
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. Calls 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 called. This method is called 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
  • Available in OS X v10.0 and later.
Declared In
NSDocumentController.h

runModalOpenPanel:forTypes:

Calls 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 called by the URLsFromRunningOpenPanel method. The extensions parameter may also contain encoded HFS file types as well as filename extensions.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocumentController.h

saveAllDocuments:

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

- (void)saveAllDocuments:(id)sender
Availability
  • Available in OS X v10.0 and later.
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
  • Available in OS X v10.4 and later.
Related Sample Code
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
  • Available in OS X v10.4 and later.
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
  • Available in OS X v10.0 and later.
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 the underlying method on super in their implementation for items they don’t handle themselves.

Availability
  • Available in OS X v10.0 and later.
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
  • Available in OS X v10.4 and later.
Declared In
NSDocumentController.h