Mac Developer Library

Developer

AppKit Framework Reference NSDocumentController Class Reference

Options
Deployment Target:

On This Page
Language:

NSDocumentController

Inheritance


Conforms To


Import Statement


Swift

import AppKit

Objective-C

@import AppKit;

Availability


Available in OS X v10.0 and later.

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.

  • Returns the shared NSDocumentController instance.

    Declaration

    Swift

    class func sharedDocumentController() -> AnyObject

    Objective-C

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

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • init() - init Designated Initializer

    This method is the designated initializer for NSDocumentController.

    Declaration

    Swift

    init()

    Objective-C

    - (instancetype)init

    Return Value

    The initialized document controller object.

    Discussion

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

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

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

    Declaration

    Swift

    func documentForURL(_ absoluteURL: NSURL) -> AnyObject?

    Objective-C

    - (id)documentForURL:(NSURL *)absoluteURL

    Parameters

    absoluteURL

    The URL of the document you wish to look up.

    Return Value

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

    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.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

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

    Declaration

    Swift

    func duplicateDocumentWithContentsOfURL(_ url: NSURL, copying duplicateByCopying: Bool, displayName displayNameOrNil: String?, error outError: NSErrorPointer) -> NSDocument?

    Objective-C

    - (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 YEStrue, 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 nil if the document could not be created.

    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.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

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

    Declaration

    Swift

    func openDocumentWithContentsOfURL(_ url: NSURL, display displayDocument: Bool, completionHandler completionHandler: (NSDocument!, Bool, NSError!) -> Void)

    Objective-C

    - (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 YEStrue, 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 YEStrue 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 YEStrue. If the relevant document class returns YEStrue 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.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

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

    Declaration

    Swift

    func openUntitledDocumentAndDisplay(_ displayDocument: Bool, error outError: NSErrorPointer) -> AnyObject?

    Objective-C

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

    Parameters

    displayDocument

    YEStrue if the user interface for the document should be shown, otherwise NOfalse.

    outError

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

    Return Value

    Returns the new NSDocument 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 YEStrue, it then sends the new document makeWindowControllers and showWindows messages.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

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

    Declaration

    Swift

    func makeDocumentForURL(_ absoluteDocumentURL: NSURL?, withContentsOfURL absoluteDocumentContentsURL: NSURL, ofType typeName: String, error outError: NSErrorPointer) -> AnyObject?

    Objective-C

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

    Parameters

    absoluteDocumentURL

    The location of the new document object.

    absoluteDocumentContentsURL

    The URL of the file that provides the contents for the new document.

    typeName

    The type of the document.

    outError

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

    Return Value

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

    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.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

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

    Declaration

    Swift

    func makeDocumentWithContentsOfURL(_ absoluteURL: NSURL, ofType typeName: String, error outError: NSErrorPointer) -> AnyObject?

    Objective-C

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

    Parameters

    absoluteURL

    The location of the new document object.

    typeName

    The type of the document.

    outError

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

    Return Value

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

    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.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

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

    Declaration

    Swift

    func makeUntitledDocumentOfType(_ typeName: String, error outError: NSErrorPointer) -> AnyObject?

    Objective-C

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

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

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

    Declaration

    Swift

    func reopenDocumentForURL(_ urlOrNil: NSURL?, withContentsOfURL contentsURL: NSURL, display displayDocument: Bool, completionHandler completionHandler: (NSDocument!, Bool, NSError!) -> Void)

    Objective-C

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

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • documents documents Property

    The document objects managed by the receiver. (read-only)

    Declaration

    Swift

    var documents: [AnyObject] { get }

    Objective-C

    @property(readonly, copy) NSArray *documents

    Discussion

    The array contains zero or more NSDocument objects.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Adds the given document to the list of open documents.

    Declaration

    Swift

    func addDocument(_ document: NSDocument)

    Objective-C

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

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • The document object associated with the main window. (read-only)

    Declaration

    Swift

    var currentDocument: AnyObject? { get }

    Objective-C

    @property(readonly, strong) id currentDocument

    Discussion

    The value of this property is nil if it is called when the app 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];

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

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

    Declaration

    Swift

    func documentForWindow(_ window: NSWindow) -> AnyObject?

    Objective-C

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

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • A Boolean value indicating whether the receiver has any documents with unsaved changes. (read-only)

    Declaration

    Swift

    var hasEditedDocuments: Bool { get }

    Objective-C

    @property(readonly) BOOL hasEditedDocuments

    Discussion

    The value of this property is YEStrue if the document controller contains documents with unsaved changes; otherwise, the value is NOfalse.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

    See Also

    documents

  • Removes the given document from the list of open documents.

    Declaration

    Swift

    func removeDocument(_ document: NSDocument)

    Objective-C

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

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • An array of strings representing the custom document classes supported by this app. (read-only)

    Declaration

    Swift

    var documentClassNames: [AnyObject] { get }

    Objective-C

    @property(readonly, copy) NSArray *documentClassNames

    Discussion

    The items in the array are NSString objects, each of which represents the name of a document subclasses supported by the app. The document class names are derived from the app’s Info.plist. You can override this property and use it to return the names of document classes that are dynamically loaded from plugins.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

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

    Declaration

    Swift

    func defaultType() -> String?

    Objective-C

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

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • Returns the NSDocument subclass associated with a given document type.

    Declaration

    Swift

    func documentClassForType(_ documentTypeName: String) -> AnyClass?

    Objective-C

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

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

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

    Declaration

    Swift

    func displayNameForType(_ documentTypeName: String) -> String?

    Objective-C

    - (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";

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

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

    Declaration

    Swift

    func typeForContentsOfURL(_ url: NSURL, error outError: NSErrorPointer) -> String?

    Objective-C

    - (NSString *)typeForContentsOfURL:(NSURL *)url 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.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • The time interval (in seconds) for periodic autosaving.

    Declaration

    Swift

    var autosavingDelay: NSTimeInterval

    Objective-C

    @property NSTimeInterval autosavingDelay

    Discussion

    A value of 0 indicates that periodic autosaving should not be done at all. The NSDocumentController object 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.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

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

    Declaration

    Swift

    func closeAllDocumentsWithDelegate(_ delegate: AnyObject?, didCloseAllSelector didCloseAllSelector: Selector, contextInfo contextInfo: UnsafeMutablePointer<Void>)

    Objective-C

    - (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 YEStrue if all documents are closed, and NOfalse 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

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

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

    Declaration

    Swift

    func reviewUnsavedDocumentsWithAlertTitle(_ title: String?, cancellable cancellable: Bool, delegate delegate: AnyObject?, didReviewAllSelector didReviewAllSelector: Selector, contextInfo contextInfo: UnsafeMutablePointer<Void>)

    Objective-C

    - (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 YEStrue if quit without saving is chosen or if there are no dirty documents, and NOfalse 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

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

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

    Declaration

    Swift

    @IBAction func newDocument(_ sender: AnyObject?)

    Objective-C

    - (IBAction)newDocument:(id)sender

    Discussion

    This method calls openUntitledDocumentAndDisplay:error:.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

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

    Declaration

    Swift

    @IBAction func openDocument(_ sender: AnyObject?)

    Objective-C

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

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

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

    Declaration

    Swift

    @IBAction func saveAllDocuments(_ sender: AnyObject?)

    Objective-C

    - (IBAction)saveAllDocuments:(id)sender

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

    See Also

    saveDocument: (NSDocument)

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

    Declaration

    Swift

    func beginOpenPanelWithCompletionHandler(_ completionHandler: ([AnyObject]!) -> Void)

    Objective-C

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

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.8 and later.

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

    Declaration

    Swift

    func beginOpenPanel(_ openPanel: NSOpenPanel, forTypes inTypes: [AnyObject], completionHandler completionHandler: (Int) -> Void)

    Objective-C

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

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.8 and later.

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

    Declaration

    Swift

    func runModalOpenPanel(_ openPanel: NSOpenPanel, forTypes types: [AnyObject]) -> Int

    Objective-C

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

    Discussion

    This method is called by the URLsFromRunningOpenPanel method. The extensions parameter may also contain encoded HFS file types as well as filename extensions.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • The directory path to be used as the starting point in the Open panel. (read-only)

    Declaration

    Swift

    var currentDirectory: String? { get }

    Objective-C

    @property(readonly, copy) 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

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • An array of URLs corresponding to the files selected in a running open panel. (read-only)

    Declaration

    Swift

    var URLsFromRunningOpenPanel: [AnyObject]? { get }

    Objective-C

    @property(readonly, copy) NSArray *URLsFromRunningOpenPanel

    Discussion

    Accessing this property creates an NSOpenPanel object and runs it using the runModalOpenPanel:forTypes: method. When the user dismisses the panel, the returned value is an array of URLs corresponding to the files chosen by the user. The value is nil if the user cancels the Open panel or makes no selection.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • The maximum number of items that may be presented in the standard Open Recent menu. (read-only)

    Declaration

    Swift

    var maximumRecentDocumentCount: Int { get }

    Objective-C

    @property(readonly) 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.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • Empties the recent documents list for the application.

    Declaration

    Swift

    @IBAction func clearRecentDocuments(_ sender: AnyObject?)

    Objective-C

    - (IBAction)clearRecentDocuments:(id)sender

    Discussion

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

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

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

    Declaration

    Swift

    func noteNewRecentDocumentURL(_ url: NSURL)

    Objective-C

    - (void)noteNewRecentDocumentURL:(NSURL *)url

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

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

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

    Declaration

    Swift

    func noteNewRecentDocument(_ document: NSDocument)

    Objective-C

    - (void)noteNewRecentDocument:(NSDocument *)document

    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.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • The list of recent-document URLs. (read-only)

    Declaration

    Swift

    var recentDocumentURLs: [AnyObject] { get }

    Objective-C

    @property(readonly, copy) NSArray *recentDocumentURLs

    Discussion

    This property contains an array of NSURL objects corresponding to the recently opened documents. Do not override this property.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

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

    Declaration

    Swift

    func validateUserInterfaceItem(_ anItem: NSValidatedUserInterfaceItem) -> Bool

    Objective-C

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

    Parameters

    anItem

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

    Return Value

    YEStrue if anItem should be enabled, otherwise NOfalse.

    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.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

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

    Declaration

    Swift

    func presentError(_ error: NSError) -> Bool

    Objective-C

    - (BOOL)presentError:(NSError *)error

    Parameters

    error

    An object containing the error that should be presented.

    Return Value

    Returns YEStrue if error recovery was done, NOfalse 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:.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

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

    Declaration

    Swift

    func presentError(_ error: NSError, modalForWindow window: NSWindow, delegate delegate: AnyObject?, didPresentSelector didPresentSelector: Selector, contextInfo contextInfo: UnsafeMutablePointer<Void>)

    Objective-C

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

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

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

    Declaration

    Swift

    func willPresentError(_ error: NSError) -> NSError

    Objective-C

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

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • Returns the document object for the file in which the document data is stored.

    Deprecation Statement

    Use documentForURL: instead.

    Declaration

    Objective-C

    - (id)documentForFileName:(NSString *)fileName

    Discussion

    The fileName argument is a fully qualified path in the file system. Returns nil if no document can be found.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

  • Returns the allowable file extensions for the given document type.

    Deprecation Statement

    Use the NSDocument method fileNameExtensionForType:saveOperation: instead.

    Declaration

    Objective-C

    - (NSArray *)fileExtensionsFromType:(NSString *)documentTypeName

    Parameters

    documentTypeName

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

    Return Value

    The allowable file extensions (as NSString objects) for documentTypeName.

    Discussion

    Type extensions are specified by the CFBundleTypeExtensions array for the given type in the Info.plist file.

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

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.5.

  • Returns a selection of files chosen by the user in the Open panel.

    Deprecation Statement

    Use URLsFromRunningOpenPanel instead.

    Declaration

    Objective-C

    - (NSArray *)fileNamesFromRunningOpenPanel

    Discussion

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

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

  • Creates and returns a document object for document type.

    Deprecation Statement

    Use makeUntitledDocumentOfType:error: instead.

    Declaration

    Objective-C

    - (id)makeUntitledDocumentOfType:(NSString *)type

    Discussion

    Creates and returns an NSDocument object for document type type. The returned object is not retained. Returns nil if the NSDocument subclass for type couldn’t be determined or if the object couldn’t be created. This method calls the NSDocument init method and is called by openUntitledDocumentOfType:display:.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

  • Creates and returns a document object for the given document type from the contents of a given URL.

    Deprecation Statement

    Use makeDocumentWithContentsOfURL:ofType:error: instead.

    Declaration

    Objective-C

    - (id)makeDocumentWithContentsOfURL:(NSURL *)url ofType:(NSString *)type

    Discussion

    Creates and returns an NSDocument object for document type docType from the contents of aURL. The returned object is not retained. Returns nil if the NSDocument subclass for docType couldn’t be determined or if the object couldn’t be created. This method calls the NSDocument method initWithContentsOfURL:ofType: and is called by openDocumentWithContentsOfURL:display:.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

  • Creates and returns a document object of a given document type from the contents of a file.

    Deprecation Statement

    Use makeDocumentWithContentsOfURL:ofType:error: instead.

    Declaration

    Objective-C

    - (id)makeDocumentWithContentsOfFile:(NSString *)fileName ofType:(NSString *)type

    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. The returned object is not retained. Returns nil if the NSDocument subclass for docType couldn’t be determined or if the object couldn’t be created. This method calls the NSDocument method initWithContentsOfFile:ofType: and is called by openDocumentWithContentsOfFile:display:.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

  • Returns a document object created from the contents of a given file and optionally displays it.

    Declaration

    Objective-C

    - (id)openDocumentWithContentsOfFile:(NSString *)fileName display:(BOOL)display

    Discussion

    Returns an NSDocument object created from the contents of the file fileName (an absolute path) and displays it if flag is YEStrue. The returned object is not retained, but is added to the receiver’s list of managed documents. Returns nil 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 YEStrue, the document is not displayed if shouldCreateUI returns NOfalse. This method calls makeDocumentWithContentsOfFile:ofType: to obtain the created NSDocument object. If you override this method, your implementation should be prepared to handle either YEStrue or NOfalse.

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

    Called with a display argument of YEStrue instead of NOfalse when a Print Documents Apple event is handled. This may have been handled differently in versions of OS X prior to version 10.3.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

  • Returns a document object created from the contents of a given URL and optionally displays it.

    Declaration

    Objective-C

    - (id)openDocumentWithContentsOfURL:(NSURL *)url display:(BOOL)display

    Discussion

    Returns an NSDocument object created from the contents of aURL and displays it if flag is YEStrue. The returned object is not retained, but is added to the receiver’s list of managed documents. Returns nil if the object could not be created, typically because aURL does not point to a valid location or because there is no NSDocument subclass for the document type. Even if flag is YEStrue, the document is not displayed if shouldCreateUI returns NOfalse. This method calls makeDocumentWithContentsOfURL:ofType: to obtain the created NSDocument object.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

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

    Declaration

    Objective-C

    - (id)openDocumentWithContentsOfURL:(NSURL *)url 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, calls makeDocumentWithContentsOfURL:ofType:error: to instantiate it, then calls addDocument: to record its opening, and sends the document makeWindowControllers and showWindows messages if displayDocument is YEStrue. If the document is already open it is just sent a showWindows message if displayDocument is YEStrue.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.4 and later.

    Deprecated in OS X v10.7.

  • Returns a document object instantiated from the subclass of the given document type and optionally displays it.

    Deprecation Statement

    Use openUntitledDocumentAndDisplay:error: with defaultType instead.

    Declaration

    Objective-C

    - (id)openUntitledDocumentOfType:(NSString *)type display:(BOOL)display

    Discussion

    Returns an NSDocument object instantiated from the NSDocument subclass required by document type docType and displays it if flag is YEStrue. The returned object is not retained, but is added to the receiver’s list of managed documents. Returns nil if the object could not be created, typically because no NSDocument subclass could be found for docType. Even if flag is YEStrue, the document is not displayed if shouldCreateUI returns NOfalse. This method calls makeUntitledDocumentOfType: to obtain the created NSDocument object.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

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

    Declaration

    Objective-C

    - (BOOL)reopenDocumentForURL:(NSURL *)url withContentsOfURL:(NSURL *)contentsURL error:(NSError **)outError

    Discussion

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

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.4 and later.

    Deprecated in OS X v10.7.

  • Sets whether the window controllers of a document should be created when the document is created.

    Deprecation Statement

    Use the display parameter of openUntitledDocumentAndDisplay:error: or openDocumentWithContentsOfURL:display:completionHandler: instead.

    Declaration

    Objective-C

    - (void)setShouldCreateUI:(BOOL)flag

    Discussion

    Sets whether the window controllers (NSWindowController instances) 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 NOfalse for scripting or searching operations involving the document’s data.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

  • Returns a Boolean value that indicates whether the window controllers of a document should be created when the document is created.

    Deprecation Statement

    Use the display parameter of openUntitledDocumentAndDisplay:error: or openDocumentWithContentsOfURL:display:completionHandler: instead.

    Declaration

    Objective-C

    - (BOOL)shouldCreateUI

    Return Value

    A Boolean value that indicates whether the window controllers (NSWindowController instances) of a document should be created when the document is created.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

  • Returns the document type associated with files having extension fileExtensionOrHFSFileType.

    Deprecation Statement

    Use typeForContentsOfURL:error: instead.

    Declaration

    Objective-C

    - (NSString *)typeFromFileExtension:(NSString *)fileNameExtensionOrHFSFileType

    Discussion

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

    This method only works when passed a file name extension used in a CFBundleDocumentTypes entry that does not have an LSItemContentTypes subentry.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.5.