Mac Developer Library

Developer

AppKit Framework Reference NSDocument Class Reference

Options
Deployment Target:

On This Page
Language:

NSDocument

Inheritance


Import Statement


Swift

import AppKit

Objective-C

@import AppKit;

Availability


Available in OS X v10.0 and later.

The NSDocument abstract class defines the interface for OS X documents. A document is an object that can internally represent data displayed in a window and that can read data from and write data to a file or file package. Documents create and manage one or more window controllers and are in turn managed by a document controller. Documents respond to first-responder action messages to save, revert, and print their data.

Conceptually, a document is a container for a body of information identified by a name under which it is stored in a disk file. In this sense, however, the document is not the same as the file but is an object in memory that owns and manages the document data. In the context of AppKit, a document is an instance of a custom NSDocument subclass that knows how to represent internally, in one or more formats, persistent data that is displayed in windows.

A document can read that data from a file and write it to a file. It is also the first-responder target for many menu commands related to documents, such as Save, Revert, and Print. A document manages its window’s edited status and is set up to perform undo and redo operations. When a window is closing, the document is asked before the window delegate to approve the closing.

NSDocument is one of the triad of AppKit classes that establish an architectural basis for document-based apps (the others being NSDocumentController and NSWindowController).

Subclassing NSDocument

The NSDocument class is designed to be subclassed. That is, the NSDocument class is abstract, and your app must create at least one NSDocument subclass in order to use the document architecture. To create a useful NSDocument subclass, you must override some methods, and you can optionally override others.

The NSDocument class itself knows how to handle document data as undifferentiated lumps; although it understands that these lumps are typed, it knows nothing about particular types. In their overrides of the data-based reading and writing methods, subclasses must add the knowledge of particular types and how data of the document’s native type is structured internally. Subclasses are also responsible for the creation of the window controllers that manage document windows and for the implementation of undo and redo. The NSDocument class takes care of much of the rest, including generally managing the state of the document.

See Document-Based App Programming Guide for Mac for more information about creating subclasses of NSDocument, particularly the list of primitive methods that subclasses must override and those that you can optionally override.

Document Saving Behavior

The NSDocument class implements document saving in a way that preserves, when possible, various attributes of each document, including:

  • Creation date

  • Permissions/privileges

  • Location of the document’s icon in its parent folder’s Icon View Finder window

  • Value of the document’s Show Extension setting

Care is also taken to save documents in a way that does not break any user-created aliases that may point to documents. As a result, some methods in any class of NSDocument may be invoked with parameters that do not have the same meaning as they did in early releases of OS X. It is important that overrides of writeToURL:ofType:error: and writeToURL:ofType:forSaveOperation:originalContentsURL:error: make no assumptions about the file paths passed as parameters, including:

  • The location to which the file is being written. This location might be a hidden temporary directory.

  • The name of the file being written. It is possible that this file has no obvious relation to the document name.

  • The relation of any file being passed, including the original file, to the value in fileURL.

When updating your app to link against OS X v10.5, keep in mind that it is usually more appropriate to invoke in your app code one of the NSDocument save... methods than one of the write... methods. The write... methods are there primarily for you to override. The saveToURL:ofType:forSaveOperation:error: method that is meant always to be invoked during document saving, sets the fileModificationDate property with the file’s new modification date after it has been written (for NSSaveOperation and NSSaveAsOperation only).

Likewise, it’s usually more appropriate to invoke in your app code one of the NSDocument revert... methods than one of the read... methods. The read... methods are there primarily for you to override. The revertToContentsOfURL:ofType:error: method that is meant always to be invoked during rereading of an open document, sets the fileModificationDate property with the file’s modification date after it has been read.

iCloud Support

The NSDocument class implements the file coordination support that is required for an iCloud-enabled, document-based Mac app (see How iCloud Document Storage Works in iCloud Design Guide). In addition, this class’s methods for moving and renaming documents, new in OS X v10.8, ensure that these operations are performed in a safe manner for iCloud-enabled apps.

Multicore Considerations

In OS X v10.6 and later, NSDocument supports the ability to open multiple documents concurrently. However, this support requires the cooperation of the document object. If your document subclass is able to read specific document types independently of other similar documents, you should override the canConcurrentlyReadDocumentsOfType: class method and return YEStrue for the appropriate document types. If specific document types rely on shared state information, however, you should return NOfalse for those types.

  • init() - init Designated Initializer

    Initializes and returns an empty NSDocument object.

    Declaration

    Swift

    init()

    Objective-C

    - (instancetype)init

    Return Value

    An initialized NSDocument object.

    Discussion

    This initializer (the designated initializer) is invoked by each of the other NSDocument initialization methods.

    You can override this method to perform initialization that must be done both when creating new empty documents and when opening existing documents. Your override must invoke super to initialize private NSDocument instance variables. It must never return nil. If an error can occur during object initialization, check for the error in an override of initWithType:error:, initWithContentsOfURL:ofType:error:, or initForURL:withContentsOfURL:ofType:error:, because those methods can return NSError objects.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Initializes a document located by a URL of a specified type.

    Declaration

    Swift

    convenience init?(contentsOfURL absoluteURL: NSURL, ofType typeName: String, error outError: NSErrorPointer)

    Objective-C

    - (instancetype)initWithContentsOfURL:(NSURL *)absoluteURL ofType:(NSString *)typeName error:(NSError **)outError

    Parameters

    absoluteURL

    The URL from which the contents of the document are obtained.

    typeName

    The string that identifies the document type.

    outError

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

    Return Value

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

    Discussion

    You can override this method to customize the reopening of autosaved documents.

    This method is invoked by the NSDocumentController method makeDocumentWithContentsOfURL:ofType:error:. The default implementation of this method calls the init and readFromURL:ofType:error: methods and sets values for the fileURL, fileType, and fileModificationDate properties.

    For backward binary compatibility with OS X v10.3 and earlier, the default implementation of this method instead invokes initWithContentsOfFile:ofType: if it is overridden and the URL uses the file: scheme. It still updates the fileModificationDate property in this situation.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • Initializes a document located by a URL of a specified type, but by reading the contents for the document from a different URL.

    Declaration

    Swift

    convenience init?(forURL absoluteDocumentURL: NSURL?, withContentsOfURL absoluteDocumentContentsURL: NSURL, ofType typeName: String, error outError: NSErrorPointer)

    Objective-C

    - (instancetype)initForURL:(NSURL *)absoluteDocumentURL withContentsOfURL:(NSURL *)absoluteDocumentContentsURL ofType:(NSString *)typeName error:(NSError **)outError

    Parameters

    absoluteDocumentURL

    The URL where the document is located.

    absoluteDocumentContentsURL

    The URL from which the contents of the document are obtained.

    typeName

    The string that identifies the document type.

    outError

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

    Return Value

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

    Discussion

    The absoluteDocumentURL argument is nil if the initializing is part of the reopening of an autosaved document when the autosaved document was never explicitly saved.

    During reopening of autosaved documents, this method uses the following NSDocumentChangeType constant to indicate that an autosaved document is being reopened:

    NSChangeReadOtherContents

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • Initializes a document of a specified type.

    Declaration

    Swift

    convenience init?(type typeName: String, error outError: NSErrorPointer)

    Objective-C

    - (instancetype)initWithType:(NSString *)typeName error:(NSError **)outError

    Parameters

    typeName

    The string that identifies the document type.

    outError

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

    Return Value

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

    Discussion

    The default implementation of this method just invokes [self init] and [self setFileType:typeName].

    You can override this method to perform initialization that must be done when creating new documents but should not be done when opening existing documents. Your override should typically invoke super, or at least it must invoke init, the NSDocument designated initializer, to initialize the NSDocument private instance variables.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • Creates and returns a data object that contains the contents of the document, formatted to a specified type.

    Declaration

    Swift

    func dataOfType(_ typeName: String, error outError: NSErrorPointer) -> NSData?

    Objective-C

    - (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError

    Parameters

    typeName

    The string that identifies the document type.

    outError

    On return, if the data object could not be created, a pointer to an error object that encapsulates the reason it could not be created.

    Return Value

    A data object containing the document contents, or, if the data object could not be created, nil.

    Discussion

    The default implementation of this method throws an exception because at least one of the writing methods (this method, writeToURL:ofType:error:, fileWrapperOfType:error:, or writeToURL:ofType:forSaveOperation:originalContentsURL:error:) must be overridden.

    For backward binary compatibility with OS X v10.3 and earlier, the default implementation of this method instead invokes dataRepresentationOfType:typeName on self if dataRepresentationOfType: is overridden.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • Creates and returns a file wrapper that contains the contents of the document, formatted to the specified type.

    Declaration

    Swift

    func fileWrapperOfType(_ typeName: String, error outError: NSErrorPointer) -> NSFileWrapper?

    Objective-C

    - (NSFileWrapper *)fileWrapperOfType:(NSString *)typeName error:(NSError **)outError

    Parameters

    typeName

    The string that identifies the document type.

    outError

    On return, if the file wrapper could not be created, a pointer to an error object that encapsulates the reason it could not be created.

    Return Value

    A file wrapper containing the document contents, or, if the file wrapper could not be created, nil.

    Discussion

    For backward binary compatibility with OS X v10.3 and earlier, if fileWrapperRepresentationOfType: is overridden, the default implementation of this method instead invokes [self fileWrapperRepresentationOfType:typeName].

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • Sets the contents of this document by reading from data of a specified type and returns YEStrue if successful.

    Declaration

    Swift

    func readFromData(_ data: NSData, ofType typeName: String, error outError: NSErrorPointer) -> Bool

    Objective-C

    - (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError

    Parameters

    data

    The data object from which the document contents are read.

    typeName

    The string that identifies the document type.

    outError

    On return, if the document contents could not be read, a pointer to an error object that encapsulates the reason they could not be read.

    Return Value

    YEStrue if the document contents could be read; otherwise, NOfalse.

    Discussion

    The default implementation of this method throws an exception because at least one of the three reading methods (this method, readFromURL:ofType:error:, readFromFileWrapper:ofType:error:), or every method that may invoke readFromURL:ofType:error:, must be overridden.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • A Boolean value indicating whether the document’s file is completely loaded into memory. (read-only)

    Declaration

    Swift

    var entireFileLoaded: Bool { get }

    Objective-C

    @property(getter=isEntireFileLoaded, readonly) BOOL entireFileLoaded

    Return Value

    YEStrue if the document’s entire file is loaded into memory; otherwise NOfalse.

    Discussion

    The default value of this property is YEStrue, which signifies that the entire file is loaded into memory. You can override this property to return NOfalse if additional data needs to be read from the file. NSDocument may use this value to do things like prevent volume ejection or warn the user when a partially loaded file disappears from the file system.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • Subclasses may override this method to create the initial window controller(s) for the document.

    Declaration

    Swift

    func makeWindowControllers()

    Objective-C

    - (void)makeWindowControllers

    Discussion

    The base class implementation creates an NSWindowController object with windowNibName and with the document as the file’s owner if windowNibName returns a name. If you override this method to create your own window controllers, be sure to use addWindowController: to add them to the document after creating them.

    This method is called by the NSDocumentController open... methods, but you might want to call it directly in some circumstances.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • The name of the document’s sole nib file. (read-only)

    Declaration

    Swift

    var windowNibName: String? { get }

    Objective-C

    @property(readonly, copy) NSString *windowNibName

    Discussion

    Using this name, NSDocument creates and instantiates a default instance of NSWindowController to manage the window. If your document has multiple nib files, each with its own single window, or if the default NSWindowController instance is not adequate for your purposes, you should override makeWindowControllers.

    The default value of this property is nil. Subclasses must override it to specify a nib file name.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Sent after the specified window controller loads a nib file if the receiver is the nib file’s owner.

    Declaration

    Swift

    func windowControllerDidLoadNib(_ windowController: NSWindowController)

    Objective-C

    - (void)windowControllerDidLoadNib:(NSWindowController *)windowController

    Parameters

    windowController

    The window controller that loads the nib file.

    Discussion

    See the class description for NSWindowController for additional information about nib files and the file’s owner object.

    Typically an NSDocument subclass overrides windowNibName or makeWindowControllers, but not both. If windowNibName is overridden, the default implementation of makeWindowControllers will load the named nib file, making the NSDocument object the nib file’s owner. In that case, you can override windowControllerDidLoadNib: and do custom processing after the nib file is loaded.

    The default implementation of this method does nothing.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Sent before the specified window controller loads a nib file if the receiver is the nib file’s owner.

    Declaration

    Swift

    func windowControllerWillLoadNib(_ windowController: NSWindowController)

    Objective-C

    - (void)windowControllerWillLoadNib:(NSWindowController *)windowController

    Parameters

    windowController

    The window controller that loads the nib file.

    Discussion

    See the class description for NSWindowController for additional information about nib files and the file’s owner object.

    Typically an NSDocument subclass overrides windowNibName or makeWindowControllers, but not both. If windowNibName is overridden, the default implementation of makeWindowControllers will load the named nib file, making the NSDocument the nib file’s owner. In that case, you can override windowControllerWillLoadNib: and do custom processing before the nib file is loaded.

    The default implementation of this method does nothing.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • The document’s current window controllers. (read-only)

    Declaration

    Swift

    var windowControllers: [AnyObject] { get }

    Objective-C

    @property(readonly, copy) NSArray *windowControllers

    Discussion

    The value of this property is an array of NSWindowController objects belonging to the current document. If there are no window controllers, the value is an empty array object.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Adds the specified window controller to this document’s list of attached window controllers and sets the document of the passed-in window controller.

    Declaration

    Swift

    func addWindowController(_ aController: NSWindowController)

    Objective-C

    - (void)addWindowController:(NSWindowController *)aController

    Parameters

    aController

    The window controller that is added.

    Discussion

    An NSDocument object uses its list of window controllers when it displays all document windows, sets window edited status upon an undo or redo operation, and modifies window titles. If you create window controllers by overriding windowNibName, this method is invoked automatically. If you create window controllers in makeWindowControllers or in any other context, such as in apps that present multiple windows per document, you should invoke this method for each window controller created.

    You cannot attach a window controller to more than one document at a time. The default implementation of this method removes the passed-in window controller from the document to which it is attached, if it is already attached to one, then sends it a setDocument: message with self as the argument. It also ignores redundant invocations.

    You would not typically override this method.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

    See Also

    setDocument: (NSWindowController)

  • Removes the specified window controller from the receiver’s array of window controllers.

    Declaration

    Swift

    func removeWindowController(_ windowController: NSWindowController)

    Objective-C

    - (void)removeWindowController:(NSWindowController *)windowController

    Parameters

    windowController

    The window controller that is removed.

    Discussion

    A document with no window controllers is not necessarily closed. However, a window controller can be set to close its associated document when the window is closed or the window controller is deallocated.

    The default implementation of this method sends a setDocument: message to the passed-in window controller with a nil argument. You would not typically override this method.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

    See Also

    shouldCloseDocument (NSWindowController)

  • Invokes shouldCloseSelector with the result of canCloseDocumentWithDelegate:shouldCloseSelector:contextInfo: if the the specified window controller that is closing is the last one or is marked as causing the document to close.

    Declaration

    Swift

    func shouldCloseWindowController(_ windowController: NSWindowController, delegate delegate: AnyObject?, shouldCloseSelector shouldCloseSelector: Selector, contextInfo contextInfo: UnsafeMutablePointer<Void>)

    Objective-C

    - (void)shouldCloseWindowController:(NSWindowController *)windowController delegate:(id)delegate shouldCloseSelector:(SEL)shouldCloseSelector contextInfo:(void *)contextInfo

    Parameters

    windowController

    The window controller that is closed.

    delegate

    The delegate to which the selector message is sent.

    shouldCloseSelector

    The selector of the message sent to the delegate.

    contextInfo

    Object passed with the callback to provide any additional context information.

    Discussion

    Otherwise it invokes shouldCloseSelector with YEStrue. This method is called automatically by NSWindow for any window that has a window controller and a document associated with it. NSWindow calls this method prior to sending its delegate the windowShouldClose: message. Pass the contextInfo object with the callback.

    The shouldCloseSelector callback method should have the following signature:

    • - (void)document:(NSDocument *)document shouldClose:(BOOL)shouldClose contextInfo:(void *)contextInfo

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Displays all of the document’s windows, bringing them to the front and making them main or key as necessary.

    Declaration

    Swift

    func showWindows()

    Objective-C

    - (void)showWindows

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Sets the window Interface Builder outlet of this class.

    Declaration

    Swift

    func setWindow(_ aWindow: NSWindow?)

    Objective-C

    - (void)setWindow:(NSWindow *)aWindow

    Parameters

    aWindow

    The window to which the receiver’s window outlet points.

    Discussion

    This method is invoked automatically during the loading of any nib for which this document is the file’s owner, if the file’s owner window outlet is connected in the nib. You should not invoke this method directly, and typically you would not override it either.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • The most appropriate window (of the windows associated with the document) to use as the parent window of a document-modal sheet. (read-only)

    Declaration

    Swift

    var windowForSheet: NSWindow? { get }

    Objective-C

    @property(readonly, strong) NSWindow *windowForSheet

    Discussion

    The value of this property may be nil, in which case the sender should present an app-modal panel. The NSDocument implementation of this property sets the value to the window of the first window controller, or [NSApp mainWindow] if there are no window controllers or if the first window controller has no window.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.3 and later.

  • The name of the document as displayed in the title bars of the document’s windows and in alert dialogs related to the document. (read-only)

    Declaration

    Swift

    var displayName: String { get }

    Objective-C

    @property(readonly, copy) NSString *displayName

    Discussion

    If the document has been saved, the display name is the last component of the directory location of the saved file (for example, “MyDocument” if the path is “/tmp/MyDocument.rtf”). If the document is new, NSDocument makes the display name “Untitled n,” where n is a number in a sequence of new and unsaved documents. The displayable name also takes into account whether the document’s filename extension should be hidden. Subclasses of NSWindowController can override windowTitleForDocumentDisplayName: to modify the display name as it appears in window titles.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Sets the name of this document for presentation to the user.

    Declaration

    Swift

    func setDisplayName(_ displayNameOrNil: String?)

    Objective-C

    - (void)setDisplayName:(NSString *)displayNameOrNil

    Parameters

    displayNameOrNil

    The display name of the document or nil, in which case the document display name is “Untitled”.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • Returns the default draft name for the receiving subclass of NSDocument.

    Declaration

    Swift

    func defaultDraftName() -> String

    Objective-C

    - (NSString *)defaultDraftName

    Discussion

    The default implementation of this method returns the string "Untitled", as adjusted according to the user’s specified locale. Your app should typically return a name that describes the kind of document. For example, a spreadsheet app could return "Spreadsheet". A document created from a template could return the name of the template, for example, "Résumé".

    When a document has not yet been assigned a name, and has not yet been autosaved with the NSAutosaveAsOperation save operation type, the document bases the default name on the value in the displayName property.

    If there is a already another document or file in the same place and with the same name as would be returned by this method, NSDocument appends a number to the defaultDraftName string.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.8 and later.

  • Sets the contents of this document by reading from a file wrapper of a specified type.

    Declaration

    Swift

    func readFromFileWrapper(_ fileWrapper: NSFileWrapper, ofType typeName: String, error outError: NSErrorPointer) -> Bool

    Objective-C

    - (BOOL)readFromFileWrapper:(NSFileWrapper *)fileWrapper ofType:(NSString *)typeName error:(NSError **)outError

    Parameters

    fileWrapper

    The file wrapper from which the document contents are read.

    typeName

    The string that identifies the document type.

    outError

    On return, if the document contents could not be read, a pointer to an error object that encapsulates the reason they could not be read.

    Return Value

    YEStrue if the document contents could be read; otherwise, NOfalse.

    Discussion

    The default implementation of this method invokes [self readFromData:[fileWrapper regularFileContents] ofType:typeName error:outError].

    For backward binary compatibility with OS X v10.3 and earlier, the default implementation of this method instead invokes [self loadFileWrapperRepresentation:fileWrapper ofType:typeName] if loadFileWrapperRepresentation:ofType: is overridden.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • The last known modification date of the document’s on-disk representation.

    Declaration

    Swift

    @NSCopying var fileModificationDate: NSDate?

    Objective-C

    @property(copy) NSDate *fileModificationDate

    Discussion

    The NSDocument default file saving machinery uses this information to warn the user when the on-disk representation of an open document has been modified by something other than the current app.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • Presents a modal Save panel to the user, then tries to save the document if the user approves the panel.

    Declaration

    Swift

    func runModalSavePanelForSaveOperation(_ saveOperation: NSSaveOperationType, delegate delegate: AnyObject?, didSaveSelector didSaveSelector: Selector, contextInfo contextInfo: UnsafeMutablePointer<Void>)

    Objective-C

    - (void)runModalSavePanelForSaveOperation:(NSSaveOperationType)saveOperation delegate:(id)delegate didSaveSelector:(SEL)didSaveSelector contextInfo:(void *)contextInfo

    Parameters

    saveOperation

    The type of save operation.

    delegate

    The delegate to which the selector message is sent.

    didSaveSelector

    The selector of the message sent to the delegate.

    contextInfo

    Object passed with the callback to provide any additional context information.

    Discussion

    When saving is completed, regardless of success or failure, or has been canceled, sends the message selected by didSaveSelector to the delegate, with contextInfo as the last argument. The method selected by didSaveSelector must have the same signature as:

    • - (void)document:(NSDocument *)doc didSave:(BOOL)didSave contextInfo:(void *)contextInfo

    Invoked from saveDocumentWithDelegate:didSaveSelector:contextInfo:, and from the saveDocumentAs: and saveDocumentTo: action methods. The default implementation of this method first makes sure that any editor registered using the Cocoa Bindings NSEditorRegistration informal protocol has committed its changes, then creates a Save panel, adds a standard file format accessory view (if there is more than one file type for the user to choose from and shouldRunSavePanelWithAccessoryView returns YEStrue), sets various attributes of the panel, invokes prepareSavePanel: to provide an opportunity for customization, then presents the panel. If the user approves the panel, the default implementation sends the message saveToURL:ofType:forSaveOperation:delegate:didSaveSelector:contextInfo:.

    For backward binary compatibility with Mac OS v10.3 and earlier, the default implementation of this method instead invokes the deprecated saveToFile:saveOperation:delegate:didSaveSelector:contextInfo: if it is overridden, even if the user cancels the panel.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • A Boolean value indicating whether the document’s Save panel displays a list of supported writable document types. (read-only)

    Declaration

    Swift

    var shouldRunSavePanelWithAccessoryView: Bool { get }

    Objective-C

    @property(readonly) BOOL shouldRunSavePanelWithAccessoryView

    Discussion

    When the value of this property is YEStrue, the document includes an a pop-up menu of supported writable document types when it displays the Save panel. The default value of this property is YEStrue. Subclasses can override this property to provide a different value. For example, you might provide the following implementation:

    • - (BOOL)shouldRunSavePanelWithAccessoryView {
    • return [self fileURL] == nil;
    • }

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • A Boolean value indicating whether the document keeps the backup files created before the document data is written to a file. (read-only)

    Declaration

    Swift

    var keepBackupFile: Bool { get }

    Objective-C

    @property(readonly) BOOL keepBackupFile

    Discussion

    The default value of this property is NOfalse, which prevents the document from keeping backup files. Subclasses can override this property and return YEStrue from their implementation to have the document keep backup files.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • The URL for the document’s backup file that was created during an autosave operation. (read-only)

    Declaration

    Swift

    @NSCopying var backupFileURL: NSURL? { get }

    Objective-C

    @property(readonly, copy) NSURL *backupFileURL

    Discussion

    This property specifies the location of the backup file, if any. If a backup file cannot be created or is not needed, the value of this property is nil.

    Starting in OS X v10.8, document versions can be preserved using a backup file created during an autosave operation, which supports document versioning. This property gives you access to the backup file’s URL.

    Using an autosave backup file for preserving versions is efficient. This is because an NSDocument instance is able to use the NSFileVersionReplacingByMoving option when it calls the replaceItemAtURL:options:error: method. The document gets the value of this property twice during saving:

    1. Before calling the writeSafelyToURL:ofType:forSaveOperation:error: method: This is to check whether using the replace-by-moving option is possible and, if not, to allow the system to preserve data by instead using copying.

    2. Within the writeSafelyToURL:ofType:forSaveOperation:error: method: This is to discover where to put the backup file.

    When you implement the writeSafelyToURL:ofType:forSaveOperation:error: method with the NSSaveOperation or NSAutosaveInPlaceOperation operation type, you must check this property’s value. If it is not nil, move the previous contents of the file (that would be overwritten) to the URL’s location. The default implementation of writeSafelyToURL:ofType:forSaveOperation:error: does this.

    To create a backup file from within your custom implementation of the writeSafelyToURL:ofType:forSaveOperation:error: method, call the NSFileManager method replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error:, using a backup item name of [[self backupFileURL] lastPathComponent] and an option of NSFileManagerItemReplacementWithoutDeletingBackupItem option. If your custom implementation is unable to keep the backup file, you must override this property and return nil to ensure that the document’s file gets correctly preserved before it gets overwritten.

    The default implementation of the writeSafelyToURL:ofType:forSaveOperation:error: method returns a non-nil value based on the value of [self fileURL], but only if the document’s file needs to be preserved prior to saving or if the preservesVersions method returns NOfalse. Otherwise, it returns nil.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.8 and later.

  • fileURL fileURL Property

    The location of the document’s on-disk representation.

    Declaration

    Swift

    @NSCopying var fileURL: NSURL?

    Objective-C

    @property(copy) NSURL *fileURL

    Return Value

    The document’s location.

    Discussion

    The default implementation of this property returns the URL of the file that was opened. Changing the value of this property does not actually change the document’s name or location; it is only for recording the document’s location during its initial opening or saving.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • draft draft Property

    A Boolean value indicating whether the document is a draft that the user has not expressed an interest in keeping around.

    Declaration

    Swift

    var draft: Bool

    Objective-C

    @property(getter=isDraft) BOOL draft

    Discussion

    The system presents a Save dialog when the user closes a draft document. Only documents with non-nil values for the fileURL property should be considered drafts.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.8 and later.

  • Sets the contents of this document by reading from a file or file package, of a specified type, located by a URL.

    Declaration

    Swift

    func readFromURL(_ absoluteURL: NSURL, ofType typeName: String, error outError: NSErrorPointer) -> Bool

    Objective-C

    - (BOOL)readFromURL:(NSURL *)absoluteURL ofType:(NSString *)typeName error:(NSError **)outError

    Parameters

    absoluteURL

    The location from which the document contents are read.

    typeName

    The string that identifies the document type.

    outError

    On return, if the document contents could not be read, a pointer to an error object that encapsulates the reason they could not be read.

    Return Value

    YEStrue if the document contents could be read; otherwise, NOfalse.

    Discussion

    The default implementation of this method just creates an NSFileWrapper and invokes [self readFromFileWrapper:theFileWrapper ofType:typeName error:outError].

    For backward binary compatibility with OS X v10.3 and earlier, the default implementation of this method instead invokes [self readFromFile:[absoluteURL path] ofType:typeName] if readFromFile:ofType: is overridden and the URL uses the file: scheme.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • Writes the contents of the document to a file or file package located by a URL, formatted to a specified type.

    Declaration

    Swift

    func writeToURL(_ absoluteURL: NSURL, ofType typeName: String, error outError: NSErrorPointer) -> Bool

    Objective-C

    - (BOOL)writeToURL:(NSURL *)absoluteURL ofType:(NSString *)typeName error:(NSError **)outError

    Parameters

    absoluteURL

    The location to which the document contents are written.

    typeName

    The string that identifies the document type.

    outError

    On return, if the document contents could not be written, a pointer to an error object that encapsulates the reason they could not be written.

    Return Value

    YEStrue if the document contents could be written; otherwise, NOfalse.

    Discussion

    The default implementation of this method just invokes [self fileWrapperOfType:typeName error:outError] and writes the returned file wrapper to disk.

    For backward binary compatibility with OS X v10.3 and earlier, the default implementation of this method instead invokes [self writeToFile:[absoluteURL path] ofType:typeName] if writeToFile:ofType: is overridden and the URL uses the file: scheme.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • Writes the contents of the document to a file or file package located by a URL.

    Declaration

    Swift

    func writeSafelyToURL(_ absoluteURL: NSURL, ofType typeName: String, forSaveOperation saveOperation: NSSaveOperationType, error outError: NSErrorPointer) -> Bool

    Objective-C

    - (BOOL)writeSafelyToURL:(NSURL *)absoluteURL ofType:(NSString *)typeName forSaveOperation:(NSSaveOperationType)saveOperation error:(NSError **)outError

    Parameters

    absoluteURL

    The location to which the document contents are written.

    typeName

    The string that identifies the document type.

    saveOperation

    The type of save operation.

    outError

    On return, if the document contents could not be written, a pointer to an error object that encapsulates the reason they could not be written.

    Return Value

    YEStrue if the document contents could be written; otherwise, NOfalse.

    Discussion

    The default implementation of this method invokes writeToURL:ofType:forSaveOperation:originalContentsURL:error:. It also invokes fileAttributesToWriteToURL:ofType:forSaveOperation:originalContentsURL:error: and writes the returned attributes, if any, to the file. It may copy some attributes from the old on-disk revision of the document at the same time, if applicable.

    This method is responsible for doing document writing in a way that minimizes the danger of leaving the disk to which writing is being done in an inconsistent state in the event of an app crash, system crash, hardware failure, power outage, and so on. If you override this method, be sure to invoke the superclass implementation.

    For NSSaveOperation, the default implementation of this method uses the value in the keepBackupFile property to determine whether or not the old on-disk revision of the document, if there was one, should be preserved after being renamed.

    For backward binary compatibility with OS X v10.3 and earlier, the default implementation of this method instead invokes writeWithBackupToFile:ofType:saveOperation: if that method is is overridden and the URL uses the file: scheme. The save operation in this case is never NSAutosaveOperation; NSSaveToOperation is used instead.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • Writes the contents of the document to a file or file package located by a URL.

    Declaration

    Swift

    func writeToURL(_ absoluteURL: NSURL, ofType typeName: String, forSaveOperation saveOperation: NSSaveOperationType, originalContentsURL absoluteOriginalContentsURL: NSURL?, error outError: NSErrorPointer) -> Bool

    Objective-C

    - (BOOL)writeToURL:(NSURL *)absoluteURL ofType:(NSString *)typeName forSaveOperation:(NSSaveOperationType)saveOperation originalContentsURL:(NSURL *)absoluteOriginalContentsURL error:(NSError **)outError

    Parameters

    absoluteURL

    The location to which the document contents are written.

    typeName

    The string that identifies the document type.

    saveOperation

    The type of save operation.

    absoluteOriginalContentsURL

    The location of the previously saved copy of the document (if not nil).

    outError

    On return, if the document contents could not be written, a pointer to an error object that encapsulates the reason they could not be written.

    Return Value

    YEStrue if the document contents could be written; otherwise, NOfalse.

    Discussion

    The default implementation of this method merely invokes [self writeToURL:absoluteURL ofType:typeName error:outError]. You can override this method instead of one of the three simple writing methods (writeToURL:ofType:error:,fileWrapperOfType:error:, and dataOfType:error:) if your document writing machinery needs access to the on-disk representation of the document revision that is about to be overwritten. The value of absoluteURL is often not the same as [self fileURL]. Other times it is not the same as the URL for the final save destination. Likewise, absoluteOriginalContentsURL is often not the same value as [self fileURL]. If absoluteOriginalContentsURL is nil, either the document has never been saved or the user deleted the document file since it was opened.

    For backward binary compatibility with OS X v10.3 and earlier, if writeToFile:ofType:originalFile:saveOperation: is overridden and both URLs use the file: scheme, the default implementation of this method instead invokes:

    • [self writeToFile:[absoluteURL path]
    •       ofType:typeName
    •       originalFile:[absoluteOriginalContentsURL path]
    •       saveOperation:aSaveOperation];

    The save operation used in this case is never NSAutosaveOperation; NSSaveToOperation is used instead.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • As a file is being saved, returns the attributes that should be written to a file or file package located by a URL, formatted to a specified type, for a particular kind of save operation.

    Declaration

    Swift

    func fileAttributesToWriteToURL(_ absoluteURL: NSURL, ofType typeName: String, forSaveOperation saveOperation: NSSaveOperationType, originalContentsURL absoluteOriginalContentsURL: NSURL?, error outError: NSErrorPointer) -> [NSObject : AnyObject]?

    Objective-C

    - (NSDictionary *)fileAttributesToWriteToURL:(NSURL *)absoluteURL ofType:(NSString *)typeName forSaveOperation:(NSSaveOperationType)saveOperation originalContentsURL:(NSURL *)absoluteOriginalContentsURL error:(NSError **)outError

    Parameters

    absoluteURL

    The location to which the document is being written.

    typeName

    The string that identifies the document type.

    saveOperation

    The type of save operation.

    absoluteOriginalContentsURL

    The location of the previously saved copy of the document (if not nil).

    outError

    On return, if the attributes could not be returned, a pointer to an error object that encapsulates the reason they could not be returned.

    Return Value

    A dictionary containing the attributes to be written, or nil if unsuccessful.

    Discussion

    Your subclass of NSDocument can override this method to control the attributes that are set during a save operation. An override of this method should return a copy of the dictionary returned by its superclass’s version of this method, with appropriate alterations.

    The set of valid file attributes is a subset of those understood by the NSFileManager class. The default implementation of this method returns an empty dictionary for an NSSaveOperation or NSAutosaveInPlaceOperation, or a dictionary with an appropriate NSFileExtensionHidden entry for any other kind of save operation. You can override this method to customize the attributes that are written to document files.

    For backward binary compatibility with OS X v10.5 and earlier, the default implementation of this method returns a dictionary with NSFileHFSCode and NSFileHFSTypeCode entries that have a value of 0 for NSSaveOperation, in apps linked against OS X v10.5 or earlier.

    For backward binary compatibility with OS X v10.3 and earlier, the default implementation of this method instead invokes [self fileAttributesToWriteToFile:[url path] ofType:typeName saveOperation:aSaveOperation] if fileAttributesToWriteToFile:ofType:saveOperation: is overridden and the URL uses the file: scheme. The save operation used in this case is never one of the autosaving ones: NSSaveToOperation is used instead.

    The default implementation of writeSafelyToURL:ofType:forSaveOperation:error: automatically copies important attributes like file permissions, creation date, and Finder information from the old on-disk version of a document to the new one during an NSSaveOperation or NSAutosaveInPlaceOperation. This method is meant to be used just for attributes that need to be written for the first time, for NSSaveAsOperation and NSSaveToOperation. The url and absoluteOriginalContentsURL parameters are passed in for completeness; NSDocument’s default implementation doesn’t need to use them.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • Saves the contents of the document to a file or file package located by a URL, formatted to a specified type, for a particular kind of save operation.

    Declaration

    Swift

    func saveToURL(_ absoluteURL: NSURL, ofType typeName: String, forSaveOperation saveOperation: NSSaveOperationType, delegate delegate: AnyObject?, didSaveSelector didSaveSelector: Selector, contextInfo contextInfo: UnsafeMutablePointer<Void>)

    Objective-C

    - (void)saveToURL:(NSURL *)absoluteURL ofType:(NSString *)typeName forSaveOperation:(NSSaveOperationType)saveOperation delegate:(id)delegate didSaveSelector:(SEL)didSaveSelector contextInfo:(void *)contextInfo

    Parameters

    absoluteURL

    The location of the file or file package to which the document contents are saved.

    typeName

    The string that identifies the document type.

    saveOperation

    The type of save operation.

    delegate

    The delegate to which the selector message is sent.

    didSaveSelector

    The selector of the message sent to the delegate.

    contextInfo

    Object passed with the callback to provide any additional context information.

    Discussion

    When saving is completed, regardless of success or failure, the method sends the message selected by didSaveSelector to the delegate, with the contextInfo as the last argument. The method selected by didSaveSelector must have the same signature as:

    • - (void)document:(NSDocument *)document didSave:(BOOL)didSaveSuccessfully contextInfo:(void *)contextInfo;

    The default implementation of this method invokes [self saveToURL:absoluteURL ofType:typeName forSaveOperation:saveOperation error:&anError] and, if NOfalse is returned, presents the error to the user in a document-modal panel before messaging the delegate.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • Returns whether the receiver can concurrently write to a file or file package located by a URL, formatted for a specific type, for a specific kind of save operation.

    Declaration

    Swift

    func canAsynchronouslyWriteToURL(_ url: NSURL, ofType typeName: String, forSaveOperation saveOperation: NSSaveOperationType) -> Bool

    Objective-C

    - (BOOL)canAsynchronouslyWriteToURL:(NSURL *)url ofType:(NSString *)typeName forSaveOperation:(NSSaveOperationType)saveOperation

    Parameters

    url

    The location of the file or package to which the document is written.

    typeName

    The string that identifies the document type.

    saveOperation

    The type of save operation.

    Return Value

    NOfalse by default; subclasses can override to return YEStrue, thereby enabling asynchronous writing.

    Discussion

    The default implementation of this method returns NOfalse. You are strongly encouraged to override it and make it return YEStrue, after making sure your overrides of document writing methods can be safely invoked on a non-main thread, and making sure that the unblockUserInteraction method is invoked at some appropriate time during writing.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • Returns an object that encapsulates the current record of document changes at the beginning of a save operation.

    Declaration

    Swift

    func changeCountTokenForSaveOperation(_ saveOperation: NSSaveOperationType) -> AnyObject

    Objective-C

    - (id)changeCountTokenForSaveOperation:(NSSaveOperationType)saveOperation

    Parameters

    saveOperation

    The type of save operation.

    Return Value

    An object encapsulating the document changes.

    Discussion

    The returned object is meant to be passed to updateChangeCountWithToken:forSaveOperation: at the end of the save operation. For example, saveToURL:ofType:forSaveOperation:completionHandler: invokes this method, on the main thread, before it does any actual saving. This method facilitates asynchronous saving, during which a user can change a document while it is being saved.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • Saves the contents of the document to a file or file package located by a URL, formatted to a specified type, for a particular kind of save operation, and invokes the passed-in completion handler.

    Declaration

    Swift

    func saveToURL(_ url: NSURL, ofType typeName: String, forSaveOperation saveOperation: NSSaveOperationType, completionHandler completionHandler: (NSError!) -> Void)

    Objective-C

    - (void)saveToURL:(NSURL *)url ofType:(NSString *)typeName forSaveOperation:(NSSaveOperationType)saveOperation completionHandler:(void (^)(NSError *errorOrNil))completionHandler

    Parameters

    url

    The location to which the document contents are written.

    typeName

    The document type.

    saveOperation

    The type of save operation.

    completionHandler

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

    The block takes one argument:

    errorOrNil

    If successful, pass a nil error. If not successful, pass an NSError object that encapsulates the reason why the document could not be saved.

    Discussion

    The default implementation of this method invokes canAsynchronouslyWriteToURL:ofType:forSaveOperation:. If writing can’t be done concurrently, it invokes writeSafelyToURL:ofType:forSaveOperation:error: on the main thread thread. If writing can be done concurrently, it invokes that method on a different thread, but blocks the main thread until something invokes unblockUserInteraction. Either way, if writeSafelyToURL:ofType:forSaveOperation:error: returns YEStrue, it updates the values in the fileModificationDate, fileType, fileURL, and autosavedContentsFileURL properties and calls the updateChangeCount: method as appropriate on the main thread. It also updates information that saveDocumentWithDelegate:didSaveSelector:contextInfo: uses to check for modification, renaming, moving, deleting, and trashing of open documents, and deletes autosaved contents files when they have become obsolete. You can override this method to do things that need to be done before or after any save operation but be sure to invoke super.

    For backward binary compatibility with OS X v10.6 and earlier, the default implementation of this method instead invokes saveToURL:ofType:forSaveOperation:error: if that method is overridden and this one is not, and it passes any error to the completion handler.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • Records the fact that saving has succeeded and updates related aspects of the change count mechanism.

    Declaration

    Swift

    func updateChangeCountWithToken(_ changeCountToken: AnyObject, forSaveOperation saveOperation: NSSaveOperationType)

    Objective-C

    - (void)updateChangeCountWithToken:(id)changeCountToken forSaveOperation:(NSSaveOperationType)saveOperation

    Parameters

    changeCountToken

    An object encapsulating the document changes, returned from changeCountTokenForSaveOperation:.

    saveOperation

    The type of save operation.

    Discussion

    This method updates the values in the documentEdited and hasUnautosavedChanges properties. For example, saveToURL:ofType:forSaveOperation:completionHandler: invokes this method, on the main thread, when it is done saving. The default implementation of this method also sends all of the document’s window controllers setDocumentEdited: messages when appropriate.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • Unblocks the main thread during asynchronous saving.

    Declaration

    Swift

    func unblockUserInteraction()

    Objective-C

    - (void)unblockUserInteraction

    Discussion

    If saveToURL:ofType:forSaveOperation:completionHandler: is writing on a non-main thread because canAsynchronouslyWriteToURL:ofType:forSaveOperation: has returned YEStrue, but it is still blocking the main thread, this method unblocks the main thread. Otherwise, it does nothing. For example, the default implementation of fileWrapperOfType:error: invokes this when it has created the NSFileWrapper object to return. Assuming that the NSFileWrapper is not mutated by subsequent user actions, it is effectively a "snapshot" of the document’s contents, and once it is created it is safe to resume handling user events on the main thread, even though some of those user events might change the document’s contents before the NSFileWrapper object has been safely written. You can invoke this method to make asynchronous saving actually asynchronous if you’ve overridden writeSafelyToURL:ofType:forSaveOperation:error:, writeToURL:ofType:forSaveOperation:originalContentsURL:error:, or writeToURL:ofType:error: in such a way that the invocation of this method done by the writeToURL:ofType:error: default implementation won’t happen during writing.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • Invokes the passed-in block to avoid a deadlock if performActivityWithSynchronousWaiting:usingBlock: is being invoked recursively.

    Declaration

    Swift

    func continueActivityUsingBlock(_ block: () -> Void)

    Objective-C

    - (void)continueActivityUsingBlock:(void (^)(void))block

    Parameters

    block

    The block to be invoked.

    Discussion

    If a block that was passed to performActivityWithSynchronousWaiting:usingBlock: is being invoked, this method invokes the passed-in block, having recorded state that makes inner invocations of performActivityWithSynchronousWaiting:usingBlock: not wait. If this method is invoked outside of an invocation of a block passed to performActivityWithSynchronousWaiting:usingBlock:, this method simply invokes the passed-in block.

    This method is useful when code executed in a block passed to performActivityWithSynchronousWaiting:usingBlock: may also invoke that method. For example, saveDocumentWithDelegate:didSaveSelector:contextInfo:, which uses performActivityWithSynchronousWaiting:usingBlock:, uses this around its invocation of runModalSavePanelForSaveOperation:delegate:didSaveSelector:contextInfo: or saveToURL:ofType:forSaveOperation:delegate:didSaveSelector:contextInfo: because both of those methods also use performActivityWithSynchronousWaiting:usingBlock:. Without the use of this method the inner invocation of performActivityWithSynchronousWaiting:usingBlock: would wait forever.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • Invokes the passed-in block on the main thread.

    Declaration

    Swift

    func continueAsynchronousWorkOnMainThreadUsingBlock(_ block: () -> Void)

    Objective-C

    - (void)continueAsynchronousWorkOnMainThreadUsingBlock:(void (^)(void))block

    Parameters

    block

    The block to be invoked.

    Discussion

    If the main thread is blocked by an invocation of performActivityWithSynchronousWaiting:usingBlock: or performSynchronousFileAccessUsingBlock:, this method interrupts that blocking to invoke the block, and then resumes blocking when the invocation of the block has returned. Invocations of this method always return before the passed-in block is invoked.

    You can invoke this method when work is being done on a non-main thread and part of the work must be continued on the main thread. For example, saveToURL:ofType:forSaveOperation:completionHandler: uses this method when it has just completed the actual writing of the file during asynchronous saving and, to finish the saving operation, must invoke updateChangeCountWithToken:forSaveOperation: and other methods on the main thread.

    This method can be invoked on any thread.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • Waits for any work scheduled by previous invocations of this method to complete, then invokes the passed-in block.

    Declaration

    Swift

    func performActivityWithSynchronousWaiting(_ waitSynchronously: Bool, usingBlock inBlock: ((() -> Void)!) -> Void)

    Objective-C

    - (void)performActivityWithSynchronousWaiting:(BOOL)waitSynchronously usingBlock:(void (^)(void (^activityCompletionHandler)(void)))inBlock

    Parameters

    waitSynchronously

    If YEStrue, the method does not return until previous activities are complete and the passed-in block has been invoked. If NOfalse, the method might return before passed-in block is invoked. It might instead be invoked later, on the main thread, after previous activities are complete.

    inBlock

    A block that performs work that might result in the presentation of a modal dialog.

    Discussion

    The block is passed another block, the activity completion handler, which must be invoked when the activity is complete.

    This method’s primary use is to wait for asynchronous saving. With asynchronous saving it is possible for the user to instigate a user interface action that might present modal dialog, a sheet for example, when asynchronous saving is about to fail and present an error alert sheet of its own, which would not work. This method solves that problem. If your NSDocument subclass supports asynchronous saving you should invoke this method around the performance of any work that might cause the presentation of a modal dialog, regardless of whether that work is performed synchronously or asynchronously. Here is a list of NSDocument methods whose default implementations invoke this method because they might present sheets, either to ask the user what to do as they begin their work or because they may fail and present errors to user:

    More uses of this method may be added to NSDocument in the future.

    This method must be invoked on the main thread. If YEStrue is passed for the waitSynchronously parameter, the method waits on the main thread, blocking further user interaction with the document. The purpose of blocking the main thread is so that the user cannot continue to change the document while an activity is pending. This prevents, for example, the situation in which the user chooses to revert the document, but reverting does not happen immediately because asynchronous saving is still in progress, yet the user is able to continue changing the document, and then those changes are immediately discarded when the asynchronous saving is complete and the document is reverted. All of the NSDocument methods listed above pass YEStrue for waitSynchronously.

    You pass NOfalse for waitSynchronously when the work to be done is instigated by the user so indirectly that the work might begin when a modal dialog is already being presented. For example, another method whose default implementation invokes this method, this time passing NOfalse for waitSynchronously, is:

    autosaveDocumentWithDelegate:didAutosaveSelector:contextInfo:

    This method might present an error alert, but it is typically invoked by a timer. If it passed YEStrue for waitSynchronously, and the timer fired while the user was looking at a sheet presented by a previous activity, blocking of the main thread would prevent the handling of the user interface events necessary to dismiss that sheet and complete that previous activity. Deadlock would result.

    Whether you make this method wait synchronously or asynchronously to do your work is separate from whether your work is done synchronously or asynchronously. For example, as mentioned above, saveToURL:ofType:forSaveOperation:delegate:didSaveSelector:contextInfo: passes YEStrue for waitSynchronously when it uses this method, even though the majority of the work it does may be done asynchronously.

    You should not invoke this method during the invocation of the block passed to performSynchronousFileAccessUsingBlock: or in between the time performAsynchronousFileAccessUsingBlock: invokes the block passed to it and the time at which the corresponding file access completion handler is invoked. If you do, deadlock can result. In other words, you cannot begin a new activity as part of file access. You can, on the other hand, invoke performSynchronousFileAccessUsingBlock: or performAsynchronousFileAccessUsingBlock: as part of an activity.

    Some asynchronous activities, such as saving, need to do work on the main thread as they are completing. A deadlock would be inevitable if there were no way to interrupt this method’s blocking of the main thread. See continueAsynchronousWorkOnMainThreadUsingBlock: to find out how to interrupt this method’s blocking of the main thread.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • Waits for any scheduled file access to complete but without blocking the main thread, then invokes the passed-in block.

    Declaration

    Swift

    func performAsynchronousFileAccessUsingBlock(_ inBlock: ((() -> Void)!) -> Void)

    Objective-C

    - (void)performAsynchronousFileAccessUsingBlock:(void (^)(void (^fileAccessCompletionHandler)(void)))inBlock

    Parameters

    inBlock

    A block that performs file access.

    Discussion

    This method does the same sort of work as performSynchronousFileAccessUsingBlock:, but without ever blocking the main thread, and may not invoke the block until after the method invocation has returned, though still always on the same thread as the method invocation. The block is passed another block, the file access completion handler, which must be invoked when the file access is complete, though it can be invoked from any thread. This method is for use with file access that might begin on one thread but continue on another before it is complete. For example, saveToURL:ofType:forSaveOperation:completionHandler: uses this method instead of performSynchronousFileAccessUsingBlock: because if it does asynchronous saving then there is no way for it to complete all of its file access before returning from the file access block.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • Waits for any scheduled file access to complete, then invokes the passed-in block.

    Declaration

    Swift

    func performSynchronousFileAccessUsingBlock(_ block: () -> Void)

    Objective-C

    - (void)performSynchronousFileAccessUsingBlock:(void (^)(void))block

    Parameters

    block

    A block that performs file access.

    Discussion

    Given a block that will perform file access, this method waits for any file access scheduled by previous invocations of this method or performAsynchronousFileAccessUsingBlock: to complete, then invokes the passed-in block. When the block invocation returns, the method allows the next scheduled file access to to be performed, if any.

    Like performActivityWithSynchronousWaiting:usingBlock:, this method’s primary use is to wait for asynchronous saving, but in contrast with that method it is only for the part of an asynchronous saving operation that actually touches the document’s file or values in memory that are relative to the document’s file.

    In general, you should use this method or performAsynchronousFileAccessUsingBlock: around code that gets or sets values in memory that only make sense in the context of the document file’s current state. For example, NSDocument itself consistently uses this mechanism when using the following methods and properties:

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • Returns a Boolean value indicating whether it is probably safe to autosave document changes.

    Declaration

    Swift

    func checkAutosavingSafetyAndReturnError(_ outError: NSErrorPointer) -> Bool

    Objective-C

    - (BOOL)checkAutosavingSafetyAndReturnError:(NSError **)outError

    Parameters

    outError

    If NOfalse is returned, a pointer to an error object that encapsulates the reason the document should not be autosaved.

    Return Value

    YEStrue if autosaving the document is probably safe; otherwise, NOfalse.

    Discussion

    The default implementation of this method checks for documents that have not been changed in a while ("a while" is subject to change) or are saved in folders where the user typically does not edit documents (the ~/Downloads folder, for example). When it senses one of those cases it returns NOfalse with an NSError object that has recovery options like Duplicate, Cancel, and Unlock.

    In an app that has adopted autosaving in place by overriding autosavesInPlace to return YEStrue, you can override this method to customize the autosaving safety checking that NSDocument does by default. You can remove the NSDocument default checking by overriding this method and not invoking super. You can add to the NSDocument default checking by invoking super and then doing your own checking if [super checkAutosavingSafetyAndReturnError:] did not signal an error. For example, TextEdit overrides this method to ask the user what to do when opening a document file has been lossy and overwriting that file might therefore be lossy.

    When autosaving in place is turned on an NSDocument object may invoke this method when it receives notification from its NSUndoManager object that the user changed the document, or undid or redid a change. If an error is returned, NSDocument presents the error to the user, allowing the user to choose a recovery option. If the user chooses a recovery option, then NSDocument invokes this method again until no error is signaled, to make sure that all checks have been done. This means that when you signal an error and the user’s choice of recovery option indicates that they have seen and disregarded a safety concern, you must record that fact and not do that particular safety check again. Once all errors are handled, NSDocument continues by invoking updateChangeCount:. If the user does not recover from an error, then NSDocument invokes one of the NSUndoManager methods undo or redo to roll back the change. So, some of the NSError recovery options the user can choose, like the NSDocument options Duplicate and Cancel, should indicate failed recovery and cause the document to remain unchanged afterward.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • Schedules periodic autosaving for the purpose of crash protection.

    Declaration

    Swift

    func scheduleAutosaving()

    Objective-C

    - (void)scheduleAutosaving

    Discussion

    The default implementation of this method checks to see if autosaving is turned on and, if so and if [self hasUnautosavedChanges] returns YEStrue, schedules an NSTimer to invoke autosaveDocumentWithDelegate:didAutosaveSelector:contextInfo: in the future. If [self hasUnautosavedChanges] returns NOfalse it unschedules any previously scheduled timer. It takes care not to cause autosaveDocumentWithDelegate:didAutosaveSelector:contextInfo: to be invoked before a previous invocation caused by it has finished. The exact timings it uses are complicated and subject to change in future releases of OS X. You can override this method to control when exactly periodic autosaving happens. It is invoked by updateChangeCount: and updateChangeCountWithToken:forSaveOperation:.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • A Boolean value indicating whether the document has changes that have not been autosaved. (read-only)

    Declaration

    Swift

    var hasUnautosavedChanges: Bool { get }

    Objective-C

    @property(readonly) BOOL hasUnautosavedChanges

    Discussion

    The value of this property is YEStrue if the document has changes that have not been autosaved; otherwise, the value is NOfalse. A document has unsaved changes when the updateChangeCount: method has been called since the last save.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • Autosaves the document’s contents at an appropriate location.

    Declaration

    Swift

    func autosaveDocumentWithDelegate(_ delegate: AnyObject?, didAutosaveSelector didAutosaveSelector: Selector, contextInfo contextInfo: UnsafeMutablePointer<Void>)

    Objective-C

    - (void)autosaveDocumentWithDelegate:(id)delegate didAutosaveSelector:(SEL)didAutosaveSelector contextInfo:(void *)contextInfo

    Parameters

    delegate

    The delegate to which the selector message is sent.

    didAutosaveSelector

    The selector of the message sent to the delegate.

    contextInfo

    Object passed with the callback to provide any additional context information.

    Discussion

    After autosaving, sends the message selected by didAutosaveSelector to the delegate, with contextInfo as the last argument. The method selected by didAutosaveSelector must have the same signature as:

    • - (void)document:(NSDocument *)document didAutosave:(BOOL)didAutosaveSuccessfully contextInfo:(void *)contextInfo

    If an error occurs while autosaving, the method reports it to the user before sending the delegate a succeeded:NO message.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • Autosaves the document’s contents at an appropriate location if it needs autosaving.

    Declaration

    Swift

    func autosaveWithImplicitCancellability(_ autosavingIsImplicitlyCancellable: Bool, completionHandler completionHandler: (NSError!) -> Void)

    Objective-C

    - (void)autosaveWithImplicitCancellability:(BOOL)autosavingIsImplicitlyCancellable completionHandler:(void (^)(NSError *errorOrNil))completionHandler

    Parameters

    autosavingIsImplicitlyCancellable

    The value in the autosavingIsImplicitlyCancellable property while autosaving is happening.

    completionHandler

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

    The block takes one argument:

    errorOrNil

    If successful, pass a nil error. If not successful, pass an NSError object that encapsulates the reason why the document could not be autosaved.

    Discussion

    The default implementation of this method does the following:

    1. Checks the value of the hasUnautosavedChanges property.

    2. If the value of that property is NOfalse, the method runs the completion handler with a nil error and returns immediately.

      If the value is YEStrue, calls autosavesInPlace on the class to determine where the autosaved document contents should go.

      The method also gets the value in fileURL to ensure that the file has an actual URL, because it is not possible to autosave in place if the document does not yet have a permanent location.

    3. Checks the value in the autosavingFileType property to determine the file type for the autosaved file.

    4. Calls saveToURL:ofType:forSaveOperation:completionHandler:.

      The value of the saveToURL parameter is the location where the file should be saved. If the file has a URL and the class specifies that autosave should occur in place, this is the URL of the file. Otherwise, this is the location of a nonexistent file in the specified autosave location.

      The value for the ofType parameter is determined by a call to autosavingFileType.

      The value of the forSaveOperation parameter is NSAutosaveInPlaceOperation if the class is configured to autosave in place and the file has a URL. Otherwise, the value is NSAutosaveElsewhereOperation.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • Returns whether the receiver supports autosaving in place.

    Declaration

    Swift

    class func autosavesInPlace() -> Bool

    Objective-C

    + (BOOL)autosavesInPlace

    Return Value

    YEStrue if the receiver supports autosaving in place; NOfalse otherwise.

    Discussion

    The default implementation of this method returns NOfalse. You can override it and return YEStrue to declare that your subclass of NSDocument can do autosaving in place. You should not invoke this method to find out whether autosaving in place is actually being done at any particular moment. You should instead use the Save Operation Types parameter that the system passes to your overrides of save and write methods.

    AppKit invokes this method at a variety of times, and not always on the main thread. For example, autosaveWithImplicitCancellability:completionHandler: invokes this method as part of determining whether the autosaving will be performed in place (NSAutosaveInPlaceOperation) or in a separate autosave directory (NSAutosaveElsewhereOperation). As another example, the canCloseDocumentWithDelegate:shouldCloseSelector:contextInfo: method and the NSDocumentController machinery for handling unsaved changes at app termination time both invoke this method as part of determining whether alerts about unsaved changes should be presented to the user.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • Returns whether the receiving subclass of NSDocument supports autosaving of drafts.

    Declaration

    Swift

    class func autosavesDrafts() -> Bool

    Objective-C

    + (BOOL)autosavesDrafts

    Return Value

    YEStrue if the receiving subclass of NSDocument supports autosaving of drafts; otherwise NOfalse.

    Discussion

    The system expects that an NSDocument subclass that returns YEStrue from this method can properly handle save operations that use the NSAutosaveAsOperation save operation type.

    The default implementation of this method returns YEStrue for apps linked on or after OS X v10.8, and returns no for apps linked against earlier versions of OS X.

    To opt out of autosaving in your NSDocument subclass when linking on or after OS X v10.8, override this method to return NOfalse.

    When linking against an OS X version prior to 10.8, you can declare that your NSDocument subclass supports autosaving by overriding this method to return YEStrue.

    AppKit invokes this method at various times. For example, when the updateChangeCount: method is called with NSChangeDone but without the NSChangeDiscardable change type, NSDocument will the next autosave to use NSAutosaveAsOperation and return the document into a draft.

    Do not invoke this method to find out whether autosaving of a draft will be done.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.8 and later.

  • Returns whether the receiving subclass of NSDocument supports Versions.

    Declaration

    Swift

    class func preservesVersions() -> Bool

    Objective-C

    + (BOOL)preservesVersions

    Return Value

    YEStrue if the receiving subclass of NSDocument supports Versions; otherwise NOfalse.

    Discussion

    The default implementation of this method returns [self autosavesInPlace]. You can override it and return NOfalse to declare that NSDocument should not preserve old document versions.

    Returning NOfalse from this method disables version browsing and revertDocumentToSaved:, which rely on version preservation when autosaving in place. Returning YEStrue from this method when autosavesInPlace returns NOfalse will result in undefined behavior.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • Opens the Versions browser in the document’s main window.

    Declaration

    Swift

    @IBAction func browseDocumentVersions(_ sender: AnyObject?)

    Objective-C

    - (IBAction)browseDocumentVersions:(id)sender

    Parameters

    sender

    The control sending the message.

    Discussion

    This is the action of the Browse Saved Versions menu item in a document-based app.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.8 and later.

  • Returns the document type that should be used for an autosave operation. (read-only)

    Declaration

    Swift

    var autosavingFileType: String? { get }

    Objective-C

    @property(readonly, copy) NSString *autosavingFileType

    Discussion

    This properties contains a string that identifies the document type for autosave files. The default implementation just returns the value provided by the fileType property. You can override this property and return nil to completely disable autosaving of individual documents (because the NSDocumentController object does not call the autosaveDocumentWithDelegate:didAutosaveSelector:contextInfo: method of a document that has no autosaving file type). You can also override it if your app defines a document type that is specifically designed for autosaving, for example, one that efficiently represents document content changes instead of complete document contents.

    Overriding this property can result in incorrect behavior during reopening of autosaved documents. The NSDocument method initForURL:withContentsOfURL:ofType:error:, which is invoked during reopening of autosaved documents after a crash, takes two URLs, but only the type name of the autosaved contents file. The default implementation updates the fileType property with that type name, but that may not be the right thing to do if this property contains something other than fileType during document autosaving. If you override autosavingFileType, you probably need to override initForURL:withContentsOfURL:ofType:error: too, and make the override update fileType with the type of the actual document file, after invoking super. See TextEdit’s Document class for an example of how to do this.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • A Boolean value indicating whether autosaving is happening now but could be safely cancelled. (read-only)

    Declaration

    Swift

    var autosavingIsImplicitlyCancellable: Bool { get }

    Objective-C

    @property(readonly) BOOL autosavingIsImplicitlyCancellable

    Discussion

    The value of this property is YEStrue if autosaving is in progress but nothing bad would happen if it were cancelled. For example, when periodic autosaving is being done only for crash protection, which doesn’t need to be done all of the time, this property is set to YEStrue. When autosaving is being done because the document is being closed, the property is set to NOfalse.

    When the value is YEStrue, your document-writing code can invoke unblockUserInteraction after recording the fact that changes to the document model made by the user should first cancel the rest of the writing. Your code that makes changes to the document model then must always do that cancellation first. If your writing code is implicitly cancelled in this way, it should set the NSError object passed by reference to the writing method to NSUserCancelledError in NSCocoaErrorDomain.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • The location of the most recently autosaved document contents.

    Declaration

    Swift

    @NSCopying var autosavedContentsFileURL: NSURL?

    Objective-C

    @property(copy) NSURL *autosavedContentsFileURL

    Discussion

    Use this property to specify the location where you want the document to store autosave files. The URL you specify should specify an absolute path, not a relative path.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • Moves the document into the user’s iCloud storage in response to the user choosing the Move to iCloud… menu item.

    Declaration

    Swift

    @IBAction func moveDocumentToUbiquityContainer(_ sender: AnyObject?)

    Objective-C

    - (IBAction)moveDocumentToUbiquityContainer:(id)sender

    Parameters

    sender

    The control sending the message.

    Discussion

    This is the action method of the Move to iCloud… menu item in a document-based app. The default implementation presents the user with an alert asking to confirm the move before invoking the moveToURL:completionHandler: method with a URL in the app’s default ubiquity container.

    See Moving Documents for descriptions of methods for moving a document to a local path.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.8 and later.

  • Returns whether your NSDocument subclass allows the use of iCloud document storage.

    Declaration

    Swift

    class func usesUbiquitousStorage() -> Bool

    Objective-C

    + (BOOL)usesUbiquitousStorage

    Discussion

    This method’s default implementation returns YEStrue if your app has a valid iCloud document storage entitlement (com.apple.developer.ubiquity-container-identifiers or com.apple.developer.icloud-container-identifiers, as described in Entitlement Key Reference). When this method returns YEStrue, the system adds new menu items and other UI for iCloud documents, as appropriate, and allows documents to be saved or moved into the primary iCloud container. (The primary iCloud container is the one identified by the first container identifier string in the iCloud Containers list in the Xcode target editor.)

    To indicate that your NSDocument subclass does not use iCloud storage, override this method to return NOfalse.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.8 and later.

  • Saves the interface-related state of the document.

    Declaration

    Swift

    func encodeRestorableStateWithCoder(_ coder: NSCoder)

    Objective-C

    - (void)encodeRestorableStateWithCoder:(NSCoder *)coder

    Parameters

    coder

    The coder object in which to save the document’s interface-related state.

    Discussion

    This method is part of the window restoration system and is called at appropriate times to save your document’s window-related state information to the specified archive. The default implementation of this method records some basic information about the document. If you override this method, you must call super at some point in your implementation.

    Subclasses can override this method and use it to restore any information that would be needed to restore the document’s window to its current state. For example, you could use this method to record references to the data currently managed by the document and displayed by the window. (Do not store the actual data itself. Store only references to the data so that you can load it later from disk.) You must store enough data to reconfigure the document and its window to their current state during a subsequent launch of the app.

    For information about using a coder object to write data to an archive, see Archives and Serializations Programming Guide.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • Restores the interface-related state of the document.

    Declaration

    Swift

    func restoreStateWithCoder(_ coder: NSCoder)

    Objective-C

    - (void)restoreStateWithCoder:(NSCoder *)coder

    Parameters

    coder

    The coder object to use to restore the document’s interface-related state.

    Discussion

    This method is part of the window restoration system and is called at launch time to restore the window-related state of your document object. The default implementation restores some basic information about the document. If you override this method, you must call super at some point in your implementation.

    Subclasses can override this method and use it to restore the document-related information that was saved in the encodeRestorableStateWithCoder: method. You can also use this method to reconfigure the document (or its associated window controller and window) to their previous appearance.

    For information about using a coder object to read data from an archive, see Archives and Serializations Programming Guide.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • Returns an array of key paths representing the restorable attributes of the document.

    Declaration

    Swift

    class func restorableStateKeyPaths() -> [AnyObject]

    Objective-C

    + (NSArray *)restorableStateKeyPaths

    Return Value

    An array of NSString objects, each of which contains a key path to one of the document’s attributes.

    Discussion

    You can use this method instead of, or in addition to, the encodeRestorableStateWithCoder: and restoreStateWithCoder: methods to save and restore the state of your document. The key paths must refer to attributes that are key-value coding and Key-value observing compliant.

    When changes are detected, the specified attributes are automatically written to disk with the rest of the app’s interface-related state. At launch time, the attributes are automatically restored to their previous values.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • Marks the document’s interface-related state as dirty.

    Declaration

    Swift

    func invalidateRestorableState()

    Objective-C

    - (void)invalidateRestorableState

    Discussion

    Call this method whenever the restorable state of your document changes. This method marks the document’s state as dirty, which causes that state to be written to disk at some point in the future. Do not override this method.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • Restores a window that was associated with a document, after that document is reopened.

    Declaration

    Swift

    func restoreDocumentWindowWithIdentifier(_ identifier: String, state state: NSCoder, completionHandler completionHandler: (NSWindow!, NSError!) -> Void)

    Objective-C

    - (void)restoreDocumentWindowWithIdentifier:(NSString *)identifier state:(NSCoder *)state completionHandler:(void (^)(NSWindow *, NSError *))completionHandler

    Parameters

    identifier

    The unique interface item identifier string that was previously associated with the window. Use this string to determine which window to create.

    state

    A coder object containing the window state information. This coder object contains the combined restorable state of the window, which can include the state of the window, its delegate, window controller, and document object. You can use this state to determine which window to create.

    completionHandler

    A block object to execute with the results of creating the window. You must execute this block at some point but may do so after the method returns if needed. This block takes the following parameters:

    • The window that was created or nil if the window could not be created.

    • An error object if the window was not recognized or could not be created for whatever reason; otherwise, specify nil.

    Discussion

    This method is called by the default NSDocumentController implementation of restoreWindowWithIdentifier:state:completionHandler:.

    The default implementation of this method first checks if the document has window controllers, and if not, it calls makeWindowControllers. If there is then exactly one window controller, it invokes the completion handler with its window. If there is more than one, it searches the receiver’s window controllers for a window that matches the given identifier, and then calls the completion handler with it. If no window could be found, it invokes the completion handler with a nil window.

    If your document has variable or optional windows, you may override this to create the requested window, and then call the completion handler with it. This allows you to use the default document reopening behavior, but intervene at the point of creating the windows. The parameters are the same as in the class method restoreWindowWithIdentifier:state:completionHandler:.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • A Boolean value indicating whether the document has changes that have not been saved. (read-only)

    Declaration

    Swift

    var documentEdited: Bool { get }

    Objective-C

    @property(getter=isDocumentEdited, readonly) BOOL documentEdited

    Discussion

    The value of this property is YEStrue if the document has been edited. The edited status of each document window reflects the document’s edited status.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.10 and later.

  • A Boolean value indicating whether the user chose to hide the name extension of the file that was selected in the Save panel for the document. (read-only)

    Declaration

    Swift

    var fileNameExtensionWasHiddenInLastRunSavePanel: Bool { get }

    Objective-C

    @property(readonly) BOOL fileNameExtensionWasHiddenInLastRunSavePanel

    Return Value

    YEStrue if a Save panel was presented and the user chose to hide the extension; otherwise, NOfalse.

    Discussion

    The value of this property is YEStrue if a Save panel was presented and the user chose to hide the extension; otherwise, the value is NOfalse.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.1 and later.

  • A Boolean value indicating whether the document is in read-only mode. (read-only)

    Declaration

    Swift

    var inViewingMode: Bool { get }

    Objective-C

    @property(getter=isInViewingMode, readonly) BOOL inViewingMode

    Discussion

    The value of this property is YEStrue if the document is in read-only "viewing mode," that is, if the document is locked. You can use this information to prevent certain kinds of user actions or changes when the user is viewing an old document revision.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • Invoked by runModalSavePanelForSaveOperation:delegate:didSaveSelector:contextInfo: to do any customization of the given Save panel.

    Declaration

    Swift

    func prepareSavePanel(_ savePanel: NSSavePanel) -> Bool

    Objective-C

    - (BOOL)prepareSavePanel:(NSSavePanel *)savePanel

    Parameters

    savePanel

    The Save panel.

    Return Value

    YEStrue if successfully prepared; otherwise, NOfalse.

    Discussion

    The default implementation is empty and returns YEStrue.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Prints the receiver in response to the user choosing the Print menu command.

    Declaration

    Swift

    @IBAction func printDocument(_ sender: AnyObject?)

    Objective-C

    - (IBAction)printDocument:(id)sender

    Parameters

    sender

    The control sending the message.

    Discussion

    An NSDocument object receives this action message as it travels up the responder chain. The default implementation invokes printDocumentWithSettings:showPrintPanel:delegate:didPrintSelector:contextInfo:.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • The action method invoked in the receiver as first responder when the user chooses the Page Setup menu command.

    Declaration

    Swift

    @IBAction func runPageLayout(_ sender: AnyObject?)

    Objective-C

    - (IBAction)runPageLayout:(id)sender

    Parameters

    sender

    The control sending the message.

    Discussion

    The default implementation invokes runModalPageLayoutWithPrintInfo:delegate:didRunSelector:contextInfo: with the document’s current NSPrintInfo object as argument; if the user clicks the OK button and the document authorizes changes to its printing information (shouldChangePrintInfo:), the method sets the document’s new NSPrintInfo object and increments the document’s change count.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • The action of the File menu item Revert in a document-based app.

    Declaration

    Swift

    @IBAction func revertDocumentToSaved(_ sender: AnyObject?)

    Objective-C

    - (IBAction)revertDocumentToSaved:(id)sender

    Parameters

    sender

    The control sending the message.

    Discussion

    The default implementation of this method presents an alert dialog giving the user the opportunity to cancel the operation. If the user chooses to continue, the method ensures that any editor registered using the Cocoa Bindings NSEditorRegistration informal protocol has discarded its changes and then invokes revertToContentsOfURL:ofType:error:. If that returns NOfalse, the method presents the error to the user in an document-modal alert dialog.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • The action method invoked in the receiver as first responder when the user chooses the Save menu command.

    Declaration

    Swift

    @IBAction func saveDocument(_ sender: AnyObject?)

    Objective-C

    - (IBAction)saveDocument:(id)sender

    Parameters

    sender

    The control sending the message.

    Discussion

    The default implementation saves the document in two different ways, depending on whether the document has a file path and a document type assigned. If path and type are assigned, it simply writes the document under its current file path and type after making a backup copy of the previous file. If the document is new (no file path and type), it runs the modal Save panel to get the file location under which to save the document. It writes the document to this file, sets the document’s file location and document type (if a native type), and clears the document’s edited status.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • The action method invoked in the receiver as first responder when the user chooses the Save As menu command.

    Declaration

    Swift

    @IBAction func saveDocumentAs(_ sender: AnyObject?)

    Objective-C

    - (IBAction)saveDocumentAs:(id)sender

    Parameters

    sender

    The control sending the message.

    Discussion

    The default implementation runs the modal Save panel to get the file location under which to save the document. It writes the document to this file, sets the document’s file location and document type (if a native type), and clears the document’s edited status.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • The action method invoked in the receiver as first responder when the user chooses the Save To menu command.

    Declaration

    Swift

    @IBAction func saveDocumentTo(_ sender: AnyObject?)

    Objective-C

    - (IBAction)saveDocumentTo:(id)sender

    Parameters

    sender

    The control sending the message.

    Discussion

    The default implementation is identical to saveDocumentAs: except that this method doesn’t clear the document’s edited status and doesn’t reset file location and document type if the document is a native type.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Saves the document.

    Declaration

    Swift

    func saveDocumentWithDelegate(_ delegate: AnyObject?, didSaveSelector didSaveSelector: Selector, contextInfo contextInfo: UnsafeMutablePointer<Void>)

    Objective-C

    - (void)saveDocumentWithDelegate:(id)delegate didSaveSelector:(SEL)didSaveSelector contextInfo:(void *)contextInfo

    Parameters

    delegate

    The delegate to which the selector message is sent.

    didSaveSelector

    The selector of the message sent to the delegate.

    contextInfo

    Object passed with the callback to provide any additional context information.

    Discussion

    If an NSSaveOperation can be performed without further user intervention (at the very least, neither fileURL nor fileType are nil), then the method immediately saves the document. Otherwise, it presents a Save panel to the user and saves the document if the user approves the panel. When saving has been completed or canceled, the method sends the message selected by didSaveSelector to the delegate, with the contextInfo as the last argument.

    As of OS X v10.5, this method checks to see if the document’s file has been modified since the document was opened or most recently saved or reverted, in addition to the checking for file moving, renaming, and trashing that it has done since OS X v10.1. When it senses file modification it presents an alert telling the user "This document’s file has been changed by another app since you opened or saved it,” giving them the choice of saving or not saving. For backward binary compatibility this is only done in apps linked against OS X v10.5 or later.

    The didSaveSelector callback method should have the following signature:

    • - (void)document:(NSDocument *)doc didSave:(BOOL)didSave contextInfo:(void *)contextInfo

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • If the receiver is not dirty, this method immediately calls the shouldCloseSelector callback on the specified delegate with YEStrue.

    Declaration

    Swift

    func canCloseDocumentWithDelegate(_ delegate: AnyObject, shouldCloseSelector shouldCloseSelector: Selector, contextInfo contextInfo: UnsafeMutablePointer<Void>)

    Objective-C

    - (void)canCloseDocumentWithDelegate:(id)delegate shouldCloseSelector:(SEL)shouldCloseSelector contextInfo:(void *)contextInfo

    Parameters

    delegate

    The delegate to which the selector message is sent.

    shouldCloseSelector

    The selector of the message sent to the delegate.

    contextInfo

    Object passed with the callback to provide any additional context information.

    Discussion

    If the receiver is dirty, an alert is presented giving the user a chance to save, not save, or cancel. If the user chooses to save, this method saves the document. If the save completes successfully, this method calls the callback with YEStrue. If the save is canceled or otherwise unsuccessful, this method calls the callback with NOfalse. This method may be called by shouldCloseWindowController:delegate:shouldCloseSelector:contextInfo:. It is also called by the NSDocumentController method closeAllDocumentsWithDelegate:didCloseAllSelector:contextInfo:. You should call it before you call close if you are closing the document and want to give the user a chance to save any edits. Pass the contextInfo object with the callback.

    The shouldCloseSelector callback method should have the following signature:

    • - (void)document:(NSDocument *)doc shouldClose:(BOOL)shouldClose contextInfo:(void *)contextInfo

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Closes all windows owned by the receiver and removes the receiver from the list of documents maintained by the document controller, which consequently releases it.

    Declaration

    Swift

    func close()

    Objective-C

    - (void)close

    Discussion

    This method closes the document immediately, without asking users if they want to save the document. This method may not always be called.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Discards all unsaved document modifications and replaces the document’s contents by reading a file or file package located by a URL of a specified type.

    Declaration

    Swift

    func revertToContentsOfURL(_ absoluteURL: NSURL, ofType typeName: String, error outError: NSErrorPointer) -> Bool

    Objective-C

    - (BOOL)revertToContentsOfURL:(NSURL *)absoluteURL ofType:(NSString *)typeName error:(NSError **)outError

    Parameters

    absoluteURL

    The location from which the document contents are read.

    typeName

    The string that identifies the document type.

    outError

    On return, if the document could not be reverted, a pointer to an error object that encapsulates the reason it could not be reverted.

    Return Value

    YEStrue if the document could be reverted; otherwise, NOfalse.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • Creates a new document whose contents are the same as the receiver and returns an error object if unsuccessful.

    Declaration

    Swift

    func duplicateAndReturnError(_ outError: NSErrorPointer) -> NSDocument?

    Objective-C

    - (NSDocument *)duplicateAndReturnError:(NSError **)outError

    Parameters

    outError

    On return, if the document could not be duplicated, a pointer to an error object that encapsulates the reason why it could not be duplicated.

    Return Value

    The new document if duplication is successful; otherwise nil.

    Discussion

    The new document returned doesn’t yet have a value to return from fileURL.

    The default implementation of this method first uses writeSafelyToURL:ofType:forSaveOperation:error: to write the document’s current contents to a file located in the same directory that is used for the autosaved contents of untitled documents and with the same sort of name, then invokes [[NSDocumentController sharedDocumentController] duplicateDocumentWithContentsOfURL:newContentsURL copying:NO displayName:aDisplayName error:outError].

    You can override this method to customize what is done during document duplication, but if your override does not invoke [NSDocumentController duplicateDocumentWithContentsOfURL:copying:displayName:error:] you must take care to do things that that method does, especially invoking [NSDocumentController addDocument:] and [NSFileCoordinator addFilePresenter:].

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • Creates a copy of the receiving document in response to the user choosing Duplicate from the File menu.

    Declaration

    Swift

    @IBAction func duplicateDocument(_ sender: AnyObject?)

    Objective-C

    - (IBAction)duplicateDocument:(id)sender

    Parameters

    sender

    The control sending the action message.

    Discussion

    The default implementation of this method merely invokes [self duplicateDocumentWithDelegate:nil didDuplicateSelector:NULL contextInfo:NULL].

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • Create a new document whose contents are the same as the receiver’s and notify the delegate.

    Declaration

    Swift

    func duplicateDocumentWithDelegate(_ delegate: AnyObject?, didDuplicateSelector didDuplicateSelector: Selector, contextInfo contextInfo: UnsafeMutablePointer<Void>)

    Objective-C

    - (void)duplicateDocumentWithDelegate:(id)delegate didDuplicateSelector:(SEL)didDuplicateSelector contextInfo:(void *)contextInfo

    Parameters

    delegate

    The delegate to which the selector message is sent.

    didDuplicateSelector

    The selector of the message sent to the delegate.

    contextInfo

    Object passed with the callback to provide any additional context information.

    Discussion

    The new document that is created doesn’t yet have a value to return from fileURL. When duplicating is completed, regardless of success or failure, or whether the operation is rejected by the user, this method sends the message indicated by didDuplicateSelector to the delegate, with contextInfo as the last argument. The method selected by didDuplicateSelector must have the same signature as:

    • - (void)document:(NSDocument *)document didDuplicate:(BOOL)didDuplicate contextInfo:(void *)contextInfo;

    The default implementation of this method first makes sure that any editor registered using the Cocoa Bindings NSEditorRegistration informal protocol has committed its changes, then checks to see if there are recent changes that might have been inadvertent and, if so, presents a panel giving the user the choice of canceling, duplicating, or duplicating then discarding recent changes. Unless the user cancels duplicating, or if no panel was presented, it then invokes duplicateAndReturnError:. If the user chose duplicating and discarding, it also discards recent changes after duplicating.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • Renames the current document in response to the user choosing the Rename menu item.

    Declaration

    Swift

    @IBAction func renameDocument(_ sender: AnyObject?)

    Objective-C

    - (IBAction)renameDocument:(id)sender

    Parameters

    sender

    The control sending the message.

    Discussion

    This is the action method of the Rename menu item in a document-based app. The default implementation of this method initiates a renaming session in a window created by the [self windowForSheet] message.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.8 and later.

  • Moves the document to a new location in response to the user choosing the Move To… menu item.

    Declaration

    Swift

    @IBAction func moveDocument(_ sender: AnyObject?)

    Objective-C

    - (IBAction)moveDocument:(id)sender

    Parameters

    sender

    The control sending the message.

    Discussion

    This is the action method of the Move To… menu item in a document-based app. By default, this method invokes the moveDocumentWithCompletionHandler: method, passing nil as a parameter value.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.8 and later.

  • Moves the document to a user-selected location.

    Declaration

    Swift

    func moveDocumentWithCompletionHandler(_ completionHandler: ((Bool) -> Void)?)

    Objective-C

    - (void)moveDocumentWithCompletionHandler:(void (^)(BOOL didMove))completionHandler

    Parameters

    completionHandler

    The completion handler block object passed in to be invoked after moving is completed, regardless of success, failure, or cancellation of moving action.

    Discussion

    This method presents the user with a move panel if [self fileURL] is non-nil and then tries to save the document to the new location by invoking the moveToURL:completionHandler: method if the user accepts the location presented by the panel. If a file with the same name already exists at that location, the user will be asked to choose between replacing the pre-existing file, renaming the current document, or canceling the move process. If [self fileURL] is nil, then the [self runModalSavePanelForSaveOperation:NSSaveAsOperation delegate:didSaveSelector:contextInfo:] message is sent instead.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.8 and later.

  • Moves the document’s file to the given URL.

    Declaration

    Swift

    func moveToURL(_ url: NSURL, completionHandler completionHandler: ((NSError!) -> Void)?)

    Objective-C

    - (void)moveToURL:(NSURL *)url completionHandler:(void (^)(NSError *))completionHandler

    Parameters

    url

    The location where the file will ultimately end up, if the move is successful.

    completionHandler

    The completion handler block object passed in to be invoked at some point in the future, perhaps after the method invocation has returned. The completion handler must be invoked on the main thread. On output, a nil error is passed if the move is successful; otherwise an NSError object is passed that encapsulates the reason for failure.

    Discussion

    The default implementation of this method replaces any file that may currently exist at the given URL with the one being moved, as necessary.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.8 and later.

  • Locks the document in response to the user choosing the Lock menu item.

    Declaration

    Swift

    @IBAction func lockDocument(_ sender: AnyObject?)

    Objective-C

    - (IBAction)lockDocument:(id)sender

    Parameters

    sender

    The control sending the message.

    Discussion

    This is the action of the Lock menu item in a document-based app. This action method invokes the lockDocumentWithCompletionHandler: method by default.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.8 and later.

  • Unlocks the document in response to the user choosing the Unlock menu item.

    Declaration

    Swift

    @IBAction func unlockDocument(_ sender: AnyObject?)

    Objective-C

    - (IBAction)unlockDocument:(id)sender

    Parameters

    sender

    The control sending the message.

    Discussion

    This is the action of the Unlock menu item in a document-based app. This action method invokes the unlockDocumentWithCompletionHandler: method by default.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.8 and later.

  • Prevents the user from making further changes to the document.

    Declaration

    Swift

    func lockDocumentWithCompletionHandler(_ completionHandler: ((Bool) -> Void)?)

    Objective-C

    - (void)lockDocumentWithCompletionHandler:(void (^)(BOOL didLock))completionHandler

    Parameters

    completionHandler

    The completion handler block object passed in to be invoked after locking is completed, regardless of success or failure of locking.

    Discussion

    By default, this method first ensures that any editor who has registered using Cocoa Binding’s NSEditorRegistration informal protocol has committed all changes and then autosaves the document, if necessary, before attempting to lock it using the lockWithCompletionHandler: method. Upon successful locking, the locked property is set to [YES]. Documents whose fileURL property is set to nil cannot be locked.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.8 and later.

  • Prevents further modifications from being made to the file.

    Declaration

    Swift

    func lockWithCompletionHandler(_ completionHandler: ((NSError!) -> Void)?)

    Objective-C

    - (void)lockWithCompletionHandler:(void (^)(NSError *))completionHandler

    Parameters

    completionHandler

    The completion handler block object passed in to be invoked after locking is completed, regardless of success or failure of locking.

    Discussion

    This method first locks the file at [self fileURL] and then invokes the given block. The default locking implementation is to enable the “user immutable” flag on the file.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.8 and later.

  • Allows the user to make modifications to the document.

    Declaration

    Swift

    func unlockDocumentWithCompletionHandler(_ completionHandler: ((Bool) -> Void)?)

    Objective-C

    - (void)unlockDocumentWithCompletionHandler:(void (^)(BOOL didUnlock))completionHandler

    Parameters

    completionHandler

    The completion handler block object passed in to be invoked after unlocking is completed, regardless of success or failure.

    Discussion

    By default, this method invokes the unlockWithCompletionHandler: method to unlock the document. This method disables autosaving safety checking, meaning that checkAutosavingSafetyAndReturnError: will no longer be invoked on this document. When unlocking succeeds, the locked method will begin returning NOfalse.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.8 and later.

  • Allows the user to make modifications to the file.

    Declaration

    Swift

    func unlockWithCompletionHandler(_ completionHandler: ((NSError!) -> Void)?)

    Objective-C

    - (void)unlockWithCompletionHandler:(void (^)(NSError *))completionHandler

    Parameters

    completionHandler

    The completion handler block object passed in to be invoked after unlocking is completed, regardless of success or failure.

    Discussion

    By default, this method tries to clear the “user immutable” flag and, if necessary, add write permissions to the file itself.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.8 and later.

  • locked locked Property

    A Boolean value indicating whether or not the file can be written to. (read-only)

    Declaration

    Swift

    var locked: Bool { get }

    Objective-C

    @property(getter=isLocked, readonly) BOOL locked

    Discussion

    This property may contain the value YEStrue because the user lacks the appropriate write permissions, the “user immutable” flag was raised, the parent directory or volume is read only, or the checkAutosavingSafetyAndReturnError: method returned NOfalse. Do not override this property.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.8 and later.

  • printInfo printInfo Property

    The printing information associated with the document.

    Declaration

    Swift

    @NSCopying var printInfo: NSPrintInfo

    Objective-C

    @property(copy) NSPrintInfo *printInfo

    Return Value

    The receiver’s NSPrintInfo object.

    Discussion

    The default value of this property is the default NSPrintInfo object. To customize the printing information, assign a new value to this property. The Page Layout panel may also update the object in this property to reflect the options selected by the user.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Invoked by runModalPageLayoutWithPrintInfo: and runModalPageLayoutWithPrintInfo:delegate:didRunSelector:contextInfo: to do any customization of the Page Layout panel pageLayout, such as adding an accessory view.

    Declaration

    Swift

    func preparePageLayout(_ pageLayout: NSPageLayout) -> Bool

    Objective-C

    - (BOOL)preparePageLayout:(NSPageLayout *)pageLayout

    Parameters

    pageLayout

    The page layout panel to prepare.

    Return Value

    YEStrue if successfully prepared; otherwise, NOfalse.

    Discussion

    The default implementation is empty and returns YEStrue.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Runs the modal page layout panel with the receiver’s printing information object

    Declaration

    Swift

    func runModalPageLayoutWithPrintInfo(_ printInfo: NSPrintInfo, delegate delegate: AnyObject?, didRunSelector didRunSelector: Selector, contextInfo contextInfo: UnsafeMutablePointer<Void>)

    Objective-C

    - (void)runModalPageLayoutWithPrintInfo:(NSPrintInfo *)printInfo delegate:(id)delegate didRunSelector:(SEL)didRunSelector contextInfo:(void *)contextInfo

    Parameters

    printInfo

    The NSPrintInfo object for the page layout panel to use.

    delegate

    The delegate to which the selector message is sent.

    didRunSelector

    The selector of the message sent to the delegate.

    contextInfo

    Object passed with the callback to provide any additional context information.

    Discussion

    Invoked from the action method runPageLayout:. Presents the page layout panel app modally if there is no document window to which it can be presented document modally.

    When the panel is dismissed, delegate is sent a didRunSelector message. The didRunSelector callback method should have the following signature:

    • - (void)documentDidRunModalPageLayout:(NSDocument *)document accepted:(BOOL)accepted contextInfo:(void *)contextInfo

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Runs the specified print operation modally.

    Declaration

    Swift

    func runModalPrintOperation(_ printOperation: NSPrintOperation, delegate delegate: AnyObject?, didRunSelector didRunSelector: Selector, contextInfo contextInfo: UnsafeMutablePointer<Void>)

    Objective-C

    - (void)runModalPrintOperation:(NSPrintOperation *)printOperation delegate:(id)delegate didRunSelector:(SEL)didRunSelector contextInfo:(void *)contextInfo

    Parameters

    printOperation

    The print operation to run.

    delegate

    The delegate to which the selector message is sent.

    didRunSelector

    The selector of the message sent to the delegate.

    contextInfo

    Object passed with the callback to provide any additional context information.

    Discussion

    Overrides of printShowingPrintPanel: can invoke this method.

    When the panel is dismissed, delegate is sent a didRunSelector message. Pass the contextInfo object with the callback. The didRunSelector callback method should have the following signature:

    • - (void)documentDidRunModalPrintOperation:(NSDocument *)document success:(BOOL)success contextInfo:(void *)contextInfo

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Returns a Boolean value indicating whether the receiver should allow changes to the default NSPrintInfo object used in printing the document.

    Declaration

    Swift

    func shouldChangePrintInfo(_ newPrintInfo: NSPrintInfo) -> Bool

    Objective-C

    - (BOOL)shouldChangePrintInfo:(NSPrintInfo *)newPrintInfo

    Parameters

    newPrintInfo

    The NSPrintInfo object that is the result of the user approving the page layout panel presented by runPageLayout:.

    Return Value

    YEStrue by default; subclasses can override this method to return NOfalse.

    Discussion

    This method is invoked by the runPageLayout: method, which sets a new NSPrintInfoobject for the document only if this method returns YEStrue.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Prints the document.

    Declaration

    Swift

    func printDocumentWithSettings(_ printSettings: [NSObject : AnyObject], showPrintPanel showPrintPanel: Bool, delegate delegate: AnyObject?, didPrintSelector didPrintSelector: Selector, contextInfo contextInfo: UnsafeMutablePointer<Void>)

    Objective-C

    - (void)printDocumentWithSettings:(NSDictionary *)printSettings showPrintPanel:(BOOL)showPrintPanel delegate:(id)delegate didPrintSelector:(SEL)didPrintSelector contextInfo:(void *)contextInfo

    Parameters

    printSettings

    The print settings dictionary to use.

    showPrintPanel

    A Boolean value indicating whether the print panel is shown.

    delegate

    The delegate to which the selector message is sent.

    didPrintSelector

    The selector of the message sent to the delegate.

    contextInfo

    Object passed with the callback to provide any additional context information.

    Discussion

    If showing of the print panel is specified by showPrintPanel, the method presents it first and prints only if the user approves the panel. The NSPrintInfo attributes in the passed-in printSettings dictionary are added to a copy of the document’s print info, and the resulting print info settings are used for the operation. When printing is complete or canceled, the method sends the message selected by didPrintSelector to the delegate, with the contextInfo as the last argument. The method selected by didPrintSelector must have the same signature as:

    • - (void)document:(NSDocument *)document didPrint:(BOOL)didPrintSuccessfully contextInfo: (void *)contextInfo

    The default implementation of this method invokes printOperationWithSettings:error:. If nil is returned it presents the error to the user in a document-modal panel before messaging the delegate. Otherwise it invokes [thePrintOperation setShowsPrintPanel:showPrintPanel] then [self runModalPrintOperation:thePrintOperation delegate:delegate didRunSelector:didPrintSelector contextInfo:contextInfo].

    For backward binary compatibility with OS X v10.3 and earlier, the default implementation of this method invokes printShowingPrintPanel: if it is overridden. When doing this it uses private functionality to arrange for the print settings to take effect (despite the fact that the override of printShowingPrintPanel: can’t possibly know about them) and to get notified when the print operation has been completed, so it can message the delegate at the correct time. Correct messaging of the delegate is necessary for correct handling of the Print Apple event.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • Creates a print operation and returns it if successful.

    Declaration

    Swift

    func printOperationWithSettings(_ printSettings: [NSObject : AnyObject], error outError: NSErrorPointer) -> NSPrintOperation?

    Objective-C

    - (NSPrintOperation *)printOperationWithSettings:(NSDictionary *)printSettings error:(NSError **)outError

    Parameters

    printSettings

    The print settings dictionary to use.

    outError

    On return, if the print operation could not be created, a pointer to an error object that encapsulates the reason it could not be created.

    Return Value

    The print operation, or nil if unsuccessful.

    Discussion

    The print operation can be run to print the document’s current contents. The NSPrintInfo attributes in the passed-in printSettings dictionary are added to a copy of the document’s print info, and the resulting print info is used for the operation.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • A print operation that you can use to create a PDF representation of the document’s current contents. (read-only)

    Declaration

    Swift

    var PDFPrintOperation: NSPrintOperation { get }

    Objective-C

    @property(readonly, strong) NSPrintOperation *PDFPrintOperation

    Discussion

    The object in this property can be run to print the document’s current contents to a PDF file.

    The default print operation stored by this property is obtained by calling the printOperationWithSettings:error: method and passing a print settings object that contains only the disposition (NSPrintSaveJob) and a NULL error object reference. If your document subclass supports creating PDF representations, you can override this property as needed to customize the options.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.9 and later.

  • Exports a PDF representation of the document’s current contents.

    Declaration

    Swift

    @IBAction func saveDocumentToPDF(_ sender: AnyObject?)

    Objective-C

    - (IBAction)saveDocumentToPDF:(id)sender

    Parameters

    sender

    The control sending the message.

    Discussion

    This action method handles the File menu’s “Export As PDF…” item in a document-based application.

    The default implementation of this method calls the printDocumentWithSettings:showPrintPanel:delegate:didPrintSelector:contextInfo: method, passing a print settings object that contains only the disposition (NSPrintSaveJob), with user interaction disabled and NULL or nil for all other parameters.

    If your document subclass supports creating PDF representations, you can override this method, if needed.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.9 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

    Parameters

    error

    The error object encapsulating the information to present to the user.

    window

    The window to which the modal alert belongs.

    delegate

    The delegate to which the selector message is sent.

    didPresentSelector

    The selector of the message sent to the delegate.

    contextInfo

    Object passed with the callback to provide any additional context information.

    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 NSDocument default implementation of this method is equivalent to that of NSResponder and treats the shared NSDocumentController object as the next responder and forwards these messages to it. The default implementations of several NSDocument methods invoke this method.

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

    The method selected by didPresentSelector must have the same signature as:

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

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

    Objective-C

    - (BOOL)presentError:(NSError *)error

    Parameters

    error

    The error object encapsulating the information to present to the user.

    Return Value

    YEStrue if error recovery was done; otherwise, NOfalse.

    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 NSDocument default implementation of this method is equivalent to that of NSResponder and treats the shared NSDocumentController as the next responder and forwards these messages to it.

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

    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.

    Declaration

    Swift

    func willPresentError(_ error: NSError) -> NSError

    Objective-C

    - (NSError *)willPresentError:(NSError *)error

    Parameters

    error

    The error object that is about to be presented to the user.

    Return Value

    The error that should actually be presented.

    Discussion

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

    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.

  • Confirms that the given NSError object is not to be presented to the user and the error cannot be recovered from, so that cleanup can be done.

    Declaration

    Swift

    func willNotPresentError(_ error: NSError)

    Objective-C

    - (void)willNotPresentError:(NSError *)error

    Parameters

    error

    An NSError object returned by another NSDocument method.

    Discussion

    Some NSDocument methods, like those involved in writing, may not immediately delete temporary files if there is a chance that the error can be recovered from and the operation can continue. To make sure that cleanup is always done, you should invoke this method with NSDocument errors that are not going to be passed to one of the presentError:... methods. For example, the NSDocument implementation of the NSFilePresenter method savePresentedItemChangesWithCompletionHandler: invokes this method when it invokes autosaveWithImplicitCancellability:completionHandler: and the completion handler is passed an NSError object, because it does not present the error to the user.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.7 and later.

  • A Boolean value indicating whether the document owns or should own an undo manager object.

    Declaration

    Swift

    var hasUndoManager: Bool

    Objective-C

    @property BOOL hasUndoManager

    Discussion

    If you change the value of this property to NO and the document already owns an NSUndoManager object, the document removes the undo manager as an observer of undo-related notifications and then removes its reference to the object.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • The document’s undo manager object.

    Declaration

    Swift

    var undoManager: NSUndoManager?

    Objective-C

    @property(strong) NSUndoManager *undoManager

    Discussion

    When the hasUndoManager property is YEStrue, accessing this property creates an NSUndoManager before returning it. If the hasUndoManager property is NOfalse, the value of this property is nil by default. Assigning an undo manager to this property stores a reference to the object and automatically changes the hasUndoManager property to YEStrue.

    Whether you assign an undo manager or let the document create one, the document registers itself as an observer of various NSUndoManager notifications so that appropriate document actions are stored on the undo stack.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Updates the receiver’s change count according to the given change type.

    Declaration

    Swift

    func updateChangeCount(_ changeType: NSDocumentChangeType)

    Objective-C

    - (void)updateChangeCount:(NSDocumentChangeType)changeType

    Parameters

    changeType

    The type of change made to the document. For a list of values, see NSDocumentChangeType.

    Discussion

    The change count indicates the document’s edited status; if the change count is 0, the document has no changes to save, and if the change count is greater than 0, the document has been edited and is unsaved. If you are implementing undo and redo in an app, you should increment the change count every time you create an undo group and decrement the change count when an undo or redo operation is performed.

    Note that if you are using the NSDocument default undo/redo features, setting the document’s edited status by updating the change count happens automatically. You only need to invoke this method when you are not using these features.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • fileType fileType Property

    The name of the document type, as specified in the app’s Info.plist file.

    Declaration

    Swift

    var fileType: String?

    Objective-C

    @property(copy) NSString *fileType

    Discussion

    The document type affects how the data is filtered when it is written to or read from a file. When a document is saved, the type is determined by the entries in the app’s information property list (specified in Info.plist).

    You cannot use this property to change the document’s format after it has already been opened or saved. This property records only the initial document format used when first opening or saving the file.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • The file type that was last selected in the Save panel. (read-only)

    Declaration

    Swift

    var fileTypeFromLastRunSavePanel: String? { get }

    Objective-C

    @property(readonly, copy) NSString *fileTypeFromLastRunSavePanel

    Discussion

    This type is primarily used by the saveDocument:, saveDocumentAs:, and saveDocumentTo: methods to determine the type the user chose after the Save panel has been run. The string corresponds to the name of the document type as it is specified in the app’s Info.plist file.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Returns a Boolean value indicating whether document data of the specified type is a native type—one the receiver can both read and write.

    Declaration

    Swift

    class func isNativeType(_ aType: String) -> Bool

    Objective-C

    + (BOOL)isNativeType:(NSString *)aType

    Parameters

    aType

    The string that identifies the document type to test.

    Return Value

    YEStrue if the document type is a native type; otherwise, NOfalse.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Returns the types of data the receiver can read natively and any types filterable to that native type.

    Declaration

    Swift

    class func readableTypes() -> [AnyObject]

    Objective-C

    + (NSArray *)readableTypes

    Return Value

    An array of NSString objects representing the readable document types.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Returns a Boolean value indicating whether the receiver reads multiple documents of the given type concurrently.

    Declaration

    Swift

    class func canConcurrentlyReadDocumentsOfType(_ typeName: String) -> Bool

    Objective-C

    + (BOOL)canConcurrentlyReadDocumentsOfType:(NSString *)typeName

    Parameters

    typeName

    The string that identifies the document type.

    Return Value

    NOfalse by default; subclasses can override to return YEStrue, thereby causing documents of the specified type to be read concurrently.

    Discussion

    Your NSDocument subclass can implement this method to return YEStrue to enable loading of documents concurrently, using background threads. When this facility is enabled in this way, initWithContentsOfURL:ofType:error: executes on a background thread when opening files via the Open panel or from the Finder. This allows concurrent reading of multiple documents and also allows the app to be responsive while reading a large document.

    The default implementation of this method returns NOfalse. A subclass override should return YEStrue only for document types whose reading is thread-safe, as described in Multicore Considerations. You should disable undo registration during document reading, which is a good idea even in the absence of concurrency.

    If you are checking the current Apple Event for a search string, you should not enable concurrent document opening, because code handling a document opening triggered by an Apple Event cannot get the current Apple Event. This happens because the event is suspended until all documents are read to enable correct reporting of success or error.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.6 and later.

    See Also

    + readableTypes

  • Returns the types of data the receiver can write natively and any types filterable to that native type.

    Declaration

    Swift

    class func writableTypes() -> [AnyObject]

    Objective-C

    + (NSArray *)writableTypes

    Return Value

    An array of NSString objects representing the writable document types.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Returns the names of the types to which this document can be saved for a specified kind of save operation.

    Declaration

    Swift

    func writableTypesForSaveOperation(_ saveOperation: NSSaveOperationType) -> [AnyObject]

    Objective-C

    - (NSArray *)writableTypesForSaveOperation:(NSSaveOperationType)saveOperation

    Parameters

    saveOperation

    The kind of save operation.

    Return Value

    An array of NSString objects representing the writable document types.

    Discussion

    The save operation type is represented by saveOperation. For every kind of save operation except NSSaveToOperation, the returned array must only include types for which the the app can play the Editor role. For NSSaveToOperation the returned array may include types for which the app can only play the Viewer role, and other types that the app can merely export. The default implementation of this method returns [[self class] writableTypes] with, except during NSSaveToOperation, types for which isNativeType: returns NOfalse filtered out.

    You can override this method to limit the set of writable types when the document currently contains data that is not representable in all types. For example, you can disallow saving to RTF files when the document contains an attachment and can only be saved properly to RTFD files.

    You can invoke this method when creating a custom save panel accessory view to present easily the same set of types as NSDocument does in its standard file format popup menu.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • Returns a filename extension that can be appended to a base filename, for a specified file type and kind of save operation.

    Declaration

    Swift

    func fileNameExtensionForType(_ typeName: String, saveOperation saveOperation: NSSaveOperationType) -> String?

    Objective-C

    - (NSString *)fileNameExtensionForType:(NSString *)typeName saveOperation:(NSSaveOperationType)saveOperation

    Parameters

    typeName

    The file type.

    saveOperation

    The kind of save operation.

    Return Value

    The filename extension.

    Discussion

    The default implementation of this method invokes preferredFilenameExtensionForType: on the shared workspace object if the type is a UTI or, if it is not, for backward binary compatibility with OS X v10.4 and earlier, invokes fileExtensionsFromType: on the shared document controller and chooses the first filename extension in the returned array.

    You can override this method to customize the appending of extensions to filenames by NSDocument. Starting in OS X v10.5, it is invoked from only two places in AppKit:

    1. The autosaveDocumentWithDelegate:didAutosaveSelector:contextInfo: method uses this method when creating a new filename for the autosaved contents.

    2. The handleSaveScriptCommand: method uses this method when adding an extension to the filename specified by a script.

    In all other cases, the name of any file being saved will have been fully specified by the user with the Save panel (whether they know it or not).

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.5 and later.

  • Validates the specified user interface item that the receiver manages.

    Declaration

    Swift

    func validateUserInterfaceItem(_ anItem: NSValidatedUserInterfaceItem) -> Bool

    Objective-C

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

    Parameters

    anItem

    The user interface item to validate.

    Return Value

    YEStrue if the item is valid; otherwise, NOfalse.

    Discussion

    These items currently include only Revert and Save. You can override this method to add more selectors validated by your document subclass.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Handles the Close AppleScript command by attempting to close the document.

    Declaration

    Swift

    func handleCloseScriptCommand(_ command: NSCloseCommand) -> AnyObject?

    Objective-C

    - (id)handleCloseScriptCommand:(NSCloseCommand *)command

    Parameters

    command

    A Close AppleScript command object.

    Discussion

    Extracts Close command arguments from the command object and uses them to determine how to close the document—specifically, whether to ignore unsaved changes, save changes automatically, or ask the user and to identify the file in which to save the document (by default, the file that was opened or previously saved to). A Close AppleScript command may specify more than one document to close. If so, a message is sent to each document object.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Handles the Print AppleScript command by attempting to print the document.

    Declaration

    Swift

    func handlePrintScriptCommand(_ command: NSScriptCommand) -> AnyObject?

    Objective-C

    - (id)handlePrintScriptCommand:(NSScriptCommand *)command

    Parameters

    command

    An AppleScript command object.

    Discussion

    Extracts Print command arguments from the command object and uses them to determine how to print the document—specifically, any print settings and whether to show the Print dialog. A Print AppleScript command may specify more than one document to print. If so, a message is sent to each document.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Handles the Save AppleScript command by attempting to save the document.

    Declaration

    Swift

    func handleSaveScriptCommand(_ command: NSScriptCommand) -> AnyObject?

    Objective-C

    - (id)handleSaveScriptCommand:(NSScriptCommand *)command

    Parameters

    command

    An AppleScript command object.

    Discussion

    Extracts Save command arguments from the command object and uses them to determine the file in which to save the document and the file type.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Returns an object specifier for the document.

    Declaration

    Swift

    var objectSpecifier: NSScriptObjectSpecifier { get }

    Objective-C

    @property(readonly, strong) NSScriptObjectSpecifier *objectSpecifier

    Return Value

    The document object specifier.

    Discussion

    An object specifier represents an AppleScript reference form, which is a natural-language expression such as words 10 through 20 or front document. During script processing, an object contained by a document (such as the second paragraph or the third rectangle) may need to specify its container (the document).

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • Returns the document name in terms of the scripting name property (the name a script writer would use to specify the document in a script).

    Declaration

    Swift

    var lastComponentOfFileName: String

    Objective-C

    @property(copy) NSString *lastComponentOfFileName

    Return Value

    The scripting name of the document.

    Discussion

    Note that this name may be different than the name of the file in fileURL or used in methods such as writeToFile:ofType:.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

    See Also

    displayName

  • Sets the document name to the given string in terms of the scripting name property (the name a script writer would use to specify the document in a script).

    Declaration

    Swift

    var lastComponentOfFileName: String

    Objective-C

    @property(copy) NSString *lastComponentOfFileName

    Parameters

    str

    The scripting name of the document.

    Discussion

    Note that this name may be different than the name used in fileURL.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

    See Also

    displayName

  • canCloseDocument - canCloseDocument Available in OS X v10.0 through OS X v10.3

    This method is no longer supported.

    Declaration

    Objective-C

    - (BOOL)canCloseDocument

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 through OS X v10.3.

    Not available to 64-bit applications.

  • A primitive method overridden by subclasses to return a data object that represents the data of the receiver in a given type.

    Deprecation Statement

    Use dataOfType:error: instead.

    Declaration

    Objective-C

    - (NSData *)dataRepresentationOfType:(NSString *)type

    Discussion

    A primitive method overridden by subclasses to return a data object that represents the data of the receiver in a given type (aType). The default implementation raises an NSInternalInconsistencyException. This method is invoked by the default implementation of fileWrapperRepresentationOfType:.

    aType is the type name corresponding to the value of the CFBundleTypeName entry in the document type’s Info.plist dictionary.

    Here is a typical implementation:

    • //Document type name
    • NSString *MyDocumentType = @"Rich Text Format (RTF) document";
    • ...
    • - (NSData *)dataRepresentationOfType:(NSString *)aType {
    • NSAssert([aType isEqualToString:MyDocumentType], @"Unknown type");
    • return [textView RTFFromRange:NSMakeRange(0, [[textView textStorage] length])];
    • }

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

  • Returns the file attributes that should be written to the named document file of the specified type.

    Declaration

    Objective-C

    - (NSDictionary *)fileAttributesToWriteToFile:(NSString *)fullDocumentPath ofType:(NSString *)documentTypeName saveOperation:(NSSaveOperationType)saveOperationType

    Discussion

    Returns the file attributes that should be written to the named document file of the specified type docType, as part of a particular saveOperationType. The set of valid file attributes is a subset of those understood by the NSFileManager class.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.1 and later.

    Deprecated in OS X v10.4.

  • fileName - fileName (OS X v10.4)

    Returns the filename (as a fully qualified path) under which the receiver has been saved.

    Deprecation Statement

    Use fileURL instead.

    Declaration

    Objective-C

    - (NSString *)fileName

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

  • Returns the filename entered into the Save panel.

    Deprecation Statement

    Use saveDocumentWithDelegate:didSaveSelector:contextInfo: instead.

    Declaration

    Objective-C

    - (NSString *)fileNameFromRunningSavePanelForSaveOperation:(NSSaveOperationType)saveOperation

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 through OS X v10.3.

    Not available to 64-bit applications.

  • Returns an NSFileWrapper object that represents the data of the receiver in a given type.

    Deprecation Statement

    Use fileWrapperOfType:error: instead.

    Declaration

    Objective-C

    - (NSFileWrapper *)fileWrapperRepresentationOfType:(NSString *)type

    Discussion

    Returns an NSFileWrapper object that represents the data of the receiver in a given type (aType). This method invokes dataRepresentationOfType: to get the data object from which to create a plain-file file wrapper. Subclasses can override this method if dataRepresentationOfType: is not adequate for their needs. This method is invoked by the default implementation of writeToFile:ofType:.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

  • Initializes and returns an NSDocument object.

    Deprecation Statement

    Use initWithContentsOfURL:ofType:error: instead.

    Declaration

    Objective-C

    - (id)initWithContentsOfFile:(NSString *)absolutePath ofType:(NSString *)typeName

    Discussion

    Initializes and returns an NSDocument object of document type docType containing data stored in the file fileName. In opening the file, invokes the readFromFile:ofType: method. If the document successfully opens the file, it updates fileURL and fileType. If the file cannot be opened, or the document is unable to load the contents of the file, this method returns nil. This initializer is typically invoked by the NSDocumentController method makeDocumentWithContentsOfFile:ofType:.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

  • Initializes and returns an NSDocument object of a given document type.

    Deprecation Statement

    Use initWithContentsOfURL:ofType:error: instead.

    Declaration

    Objective-C

    - (id)initWithContentsOfURL:(NSURL *)url ofType:(NSString *)typeName

    Discussion

    Initializes and returns an NSDocument object of document type docType containing data stored at aURL. In opening the location, invokes the readFromURL:ofType: method. If the document successfully opens the location, it updates fileURL and fileType. If the location cannot be opened, or the document is unable to load the contents of the location, this method returns nil. This initializer is typically invoked by the NSDocumentController method makeDocumentWithContentsOfURL:ofType:.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

  • Overridden by subclasses to load document data.

    Deprecation Statement

    Use readFromData:ofType:error: instead.

    Declaration

    Objective-C

    - (BOOL)loadDataRepresentation:(NSData *)data ofType:(NSString *)type

    Discussion

    Overridden by subclasses to load document data (docData) of type docType into the receiver, display it in windows, and return whether the operation was successful. This method is typically invoked by loadFileWrapperRepresentation:ofType: after an NSData object is created from the contents of the file wrapper (which can include directories). The default implementation raises an NSInternalInconsistencyException. Subclasses must override this method unless they override readFromFile:ofType: or loadFileWrapperRepresentation:ofType: to do specialized reading and loading of document data.

    The docType argument is the type name corresponding to the value of the CFBundleTypeName entry in the document type’s Info.plist dictionary.

    Here is an example implementation:

    • //Document type name
    • NSString *MyDocumentType = @"Rich Text Format (RTF) document";
    • ...
    • - (BOOL)loadDataRepresentation:(NSData *)data ofType:(NSString *)aType {
    • NSAssert([aType isEqualToString: MyDocumentType], @"Unknown type");
    • fileContents = [data copyWithZone:[self zone]];
    • return YES;
    • }

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

  • Loads document data from a given file wrapper.

    Deprecation Statement

    Use readFromFileWrapper:ofType:error: instead.

    Declaration

    Objective-C

    - (BOOL)loadFileWrapperRepresentation:(NSFileWrapper *)wrapper ofType:(NSString *)type

    Discussion

    Loads document data in file wrapper wrapper of type docType into the receiver, displays it in windows, and returns whether the operation was successful. If wrapper is a simple file, it invokes loadDataRepresentation:ofType: to load the data. If wrapper is a directory, it returns NOfalse by default; subclasses can override to handle file wrappers that are directories. This method is typically invoked by readFromFile:ofType: after it creates an NSData object from the contents of the file.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

  • Overridden by subclasses to print the current document’s (the receiver’s) data.

    Declaration

    Objective-C

    - (void)printShowingPrintPanel:(BOOL)flag

    Discussion

    Overridden by subclasses to print the current document’s (the receiver’s) data; if flag is YEStrue, the implementation should first display the Print panel. This method is typically invoked by printDocument: with an argument of YEStrue. The default implementation does nothing. If there is any printing information other than that encoded in the receiver’s NSPrintInfo object, subclasses should get it here.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

  • Reads and loads document data of the given type from the given file.

    Deprecation Statement

    Use readFromURL:ofType:error: instead.

    Declaration

    Objective-C

    - (BOOL)readFromFile:(NSString *)fileName ofType:(NSString *)type

    Discussion

    Reads and loads document data of type docType from the file fileName, returning whether the operation was successful. This method invokes loadDataRepresentation:ofType: and is invoked when the receiver is first created and initialized by initWithContentsOfFile:ofType:. It uses NSData initWithContentsOfFile: to get the document data.

    This method is one of the location-based primitives. Subclasses can override this method instead of overriding loadDataRepresentation:ofType: to read and load document data. Subclasses that handle file packages such as RTFD or that treat locations of files as anything other than paths should override this method. Override implementations of this method can filter the document data using NSPasteboard or other filtering services.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

  • Reads and loads document data.

    Deprecation Statement

    Use readFromURL:ofType:error: instead.

    Declaration

    Objective-C

    - (BOOL)readFromURL:(NSURL *)url ofType:(NSString *)type

    Discussion

    Reads and loads document data of type docType from the URL aURL, returning whether the operation was successful. This method only supports URLs of the file: scheme and calls readFromFile:ofType:.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

  • Reverts the receiver to the data stored in the file system.

    Deprecation Statement

    Use revertToContentsOfURL:ofType:error: instead.

    Declaration

    Objective-C

    - (BOOL)revertToSavedFromFile:(NSString *)fileName ofType:(NSString *)type

    Discussion

    Reverts the receiver to the data stored in the file system in file named fileName of file type type. Invokes readFromFile:ofType: and returns whether that method successfully read the file and processed the document data.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

  • Reverts the receiver.

    Deprecation Statement

    Use revertToContentsOfURL:ofType:error: instead.

    Declaration

    Objective-C

    - (BOOL)revertToSavedFromURL:(NSURL *)url ofType:(NSString *)type

    Discussion

    Reverts the receiver to the data stored at aURL of type type. Invokes readFromURL:ofType: and returns whether that method successfully read the file and processed the document data.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

  • Runs the page layout modal panel with the receiver’s printing information object.

    Declaration

    Objective-C

    - (NSInteger)runModalPageLayoutWithPrintInfo:(NSPrintInfo *)printInfo

    Discussion

    Runs the page layout modal panel with the receiver’s printing information object (printInfo) as argument and returns the result constant (indicating the button pressed by the user). To run as sheet on the receiver’s document window, use runModalPageLayoutWithPrintInfo:delegate:didRunSelector:contextInfo: instead.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

  • Called after the user has been given the opportunity to select a destination through the modal Save panel.

    Declaration

    Objective-C

    - (void)saveToFile:(NSString *)fileName saveOperation:(NSSaveOperationType)saveOperation delegate:(id)delegate didSaveSelector:(SEL)didSaveSelector contextInfo:(void *)contextInfo

    Discussion

    Called after the user has been given the opportunity to select a destination through the modal Save panel presented by runModalSavePanelForSaveOperation:delegate:didSaveSelector:contextInfo:. The delegate is assigned to the Save panel. If fileName is non-nil, this method writes the document to fileName, sets the document’s file location and document type (if a native type), and clears the document’s edited status. didSaveSelector gets called with YEStrue if the document is saved successfully, and NOfalse otherwise. The saveOperation is one of the constants in Constants. Pass contextInfo with the callback.

    The didSaveSelector callback method should have the following signature:

    • - (void)document:(NSDocument *)doc didSave:(BOOL)didSave contextInfo:(void *)contextInfo

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

  • Saves the contents of the document to a file or file package located by a URL, formatted to a specified type, for a particular kind of save operation, and returns YEStrue if successful.

    Deprecation Statement

    Use saveToURL:ofType:forSaveOperation:completionHandler: instead.

    Declaration

    Objective-C

    - (BOOL)saveToURL:(NSURL *)absoluteURL ofType:(NSString *)typeName forSaveOperation:(NSSaveOperationType)saveOperation error:(NSError **)outError

    Parameters

    absoluteURL

    The location of the file or file package to which the document contents are saved.

    typeName

    The string that identifies the document type.

    saveOperation

    The type of save operation.

    outError

    On return, if the document contents could not be saved, a pointer to an error object that encapsulates the reason they could not be saved.

    Return Value

    YEStrue if the document contents were successfully saved; otherwise, NOfalse.

    Discussion

    You can override this method to do things that need to be done before or after any save operation. If you override this method, you must call super at some point in your implementation.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.4 and later.

    Deprecated in OS X v10.6.

  • Sets the file (filename and directory path) under which document data is saved.

    Deprecation Statement

    Use setFileURL: instead.

    Declaration

    Objective-C

    - (void)setFileName:(NSString *)fileName

    Discussion

    Sets the file (filename and directory path) under which document data is saved to fileName. As a side effect, synchronizes the titles of the document’s windows with the new name or location. A document’s filename is automatically set when it is saved as a new document (Save) and when an existing document is saved under a different filename or path (Save As). The Finder also keeps track of open documents and their associated files. When a user moves or renames a file in the Finder that corresponds to an open document, the Finder calls setFileName: with the new filename.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

  • shouldCloseWindowController: - shouldCloseWindowController: Available in OS X v10.0 through OS X v10.3

    Gives the user an opportunity to save the document.

    Declaration

    Objective-C

    - (BOOL)shouldCloseWindowController:(NSWindowController *)windowController

    Discussion

    If closing the windowController would cause the receiver to be closed, invokes canCloseDocumentWithDelegate:shouldCloseSelector:contextInfo: to display a Save panel and give the user an opportunity to save the document. Returns the return value of canCloseDocumentWithDelegate:shouldCloseSelector:contextInfo:. Note that the receiver doesn’t close until its window controller closes.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 through OS X v10.3.

    Not available to 64-bit applications.

  • validateMenuItem: - validateMenuItem: Available in OS X v10.0 through OS X v10.3

    Validates the Revert menu item and items selected from the Save panel’s pop-up list of writable document types items.

    Deprecation Statement

    Use validateUserInterfaceItem: instead.

    Declaration

    Objective-C

    - (BOOL)validateMenuItem:(NSMenuItem *)anItem

    Discussion

    Returns YEStrue if anItem should be enabled, NOfalse otherwise. Returns YEStrue for Revert if the document has been edited and a file exists for the document. Returns YEStrue for an item representing a writable type if, during a Save or Save As operation, it is a native type for the document. Subclasses can override this method to perform additional validations.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 through OS X v10.3.

    Not available to 64-bit applications.

  • Writes document data to a file.

    Deprecation Statement

    Use writeToURL:ofType:error: instead.

    Declaration

    Objective-C

    - (BOOL)writeToFile:(NSString *)fileName ofType:(NSString *)type

    Discussion

    Writes document data of type docType to the file fileName, returning whether the operation was successful. This method invokes dataRepresentationOfType: and is indirectly invoked whenever the document file is saved. It uses the NSData method writeToFile:atomically: to write to the file.

    This method is one of the location-based primitives. Subclasses can override this method instead of overriding dataRepresentationOfType: to write document data to the file system as an NSData object after creating that object from internal data structures. Subclasses that handle file packages such as RTFD or that treat locations of files as anything other than paths should override this method. Override implementations of this method should ensure that they filter document data appropriately using NSPasteboard filtering services.

    See Document Saving Behavior for additional information about saving documents.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

  • Writes the receiver document’s contents to a file.

    Declaration

    Objective-C

    - (BOOL)writeToFile:(NSString *)fullDocumentPath ofType:(NSString *)documentTypeName originalFile:(NSString *)fullOriginalDocumentPath saveOperation:(NSSaveOperationType)saveOperationType

    Discussion

    This method is called from writeWithBackupToFile:ofType:saveOperation: to actually write the file of type docType to fullDocumentPath. fullOriginalDocumentPath is the path to the original file if there is one and nil otherwise. The default implementation simply calls writeToFile:ofType:. You should not need to call this method directly, but subclasses that need access to the previously saved copy of their document while saving the new one can override this method. The saveOperationType argument is one of the constants listed in Constants.

    See Document Saving Behavior for additional information about saving documents.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

  • Writes document data to a URL.

    Deprecation Statement

    Use writeToURL:ofType:error: instead.

    Declaration

    Objective-C

    - (BOOL)writeToURL:(NSURL *)url ofType:(NSString *)type

    Discussion

    Writes document data of type docType to the URL aURL, returning whether the operation was successful. This method only supports URLs of the file: scheme and calls writeToFile:ofType:.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

  • This method is called by action methods to save document contents to a file.

    Deprecation Statement

    Use writeSafelyToURL:ofType:forSaveOperation:error: instead.

    Declaration

    Objective-C

    - (BOOL)writeWithBackupToFile:(NSString *)fullDocumentPath ofType:(NSString *)documentTypeName saveOperation:(NSSaveOperationType)saveOperationType

    Discussion

    This method is called by action methods like saveDocument:, saveDocumentAs:, and saveDocumentTo:. It is responsible for handling backup of the existing file, if any, and removal of that backup if keepBackupFile returns NOfalse. In between those two things, it calls writeToFile:ofType:originalFile:saveOperation: to write the document of type docType to fullDocumentPath. You should never need to call writeWithBackupToFile:ofType:saveOperation:, but subclasses that want to change the way the backup works can override it. The saveOperationType argument is one of the constants listed in Constants.

    If you override this method, you should invoke fileAttributesToWriteToFile:ofType:saveOperation: and set the variables returned from this method when writing fullDocumentPath. NSFileManager changeFileAttributes:atPath: can be used to do this.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.4.

Data Types

  • Change counts indicate a document’s edit status. These constants indicate how a document should operate on its change count and are passed to the updateChangeCount: method.

    Declaration

    Swift

    enum NSDocumentChangeType : UInt { case ChangeDone case ChangeUndone case ChangeRedone case ChangeCleared case ChangeReadOtherContents case ChangeAutosaved case ChangeDiscardable }

    Objective-C

    typedef enum NSDocumentChangeType : NSUInteger { NSChangeDone = 0, NSChangeUndone = 1, NSChangeCleared = 2, NSChangeReadOtherContents = 3, NSChangeAutosaved = 4, NSChangeRedone = 5, NSChangeDiscardable = 256 } NSDocumentChangeType;

    Constants

    • ChangeDone

      NSChangeDone

      Increment change count. Pass this value to the updateChangeCount: method to indicate that a single change has been done. For example, the built-in undo support in the NSDocument class passes this value whenever a document receives an NSUndoManagerDidCloseUndoGroupNotification notification from its own undo manager.

      Available in OS X v10.0 and later.

    • ChangeUndone

      NSChangeUndone

      Decrement change count. A single change has been undone. For example, the built-in undo support of NSDocument passes this value whenever a document receives an NSUndoManagerDidUndoChangeNotification from its own undo manager.

      Available in OS X v10.0 and later.

    • ChangeCleared

      NSChangeCleared

      Set change count to 0. The document has been synchronized with its file or file package. For example, saveToURL:ofType:forSaveOperation:error: passes this value for a successful NSSaveOperation or NSSaveAsOperation. The revertDocumentToSaved: method does too.

      Available in OS X v10.0 and later.

    • ChangeReadOtherContents

      NSChangeReadOtherContents

      The document has been initialized with the contents of a file or file package other than the one whose location is in the fileURL property, and therefore can’t possibly be synchronized with its persistent representation. For example, initForURL:withContentsOfURL:ofType:error: passes this value when the two passed-in URLs are not equal to indicate that an autosaved document is being reopened.

      Available in OS X v10.4 and later.

    • ChangeAutosaved

      NSChangeAutosaved

      The document’s contents have been autosaved. For example, saveToURL:ofType:forSaveOperation:error: passes this value for a successful NSAutosaveOperation.

      Available in OS X v10.4 and later.

    • ChangeRedone

      NSChangeRedone

      A single change has been redone. For example, the built-in undo support of NSDocument passes this value whenever a document receives an NSUndoManagerDidRedoChangeNotification from its own undo manager.

      Available in OS X v10.5 and later.

    • ChangeDiscardable

      NSChangeDiscardable

      A discardable change has been done. Discardable changes cause the document to be edited. In a locked document, for example, discardable changes may be thrown away instead of prompting the user to save them. Combine this value with the appropriate kind of change, NSChangeDone, NSChangeUndone, or NSChangeRedone, using the C bitwise OR operator. For example, a discardable change is NSChangeDone | NSChangeDiscardable.

      Available in OS X v10.7 and later.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • A save operation type specifies the type of document save operation to perform. These values are used with method parameters of type Save Operation Types. Depending on the method, the save operation type can affect the title of the Save dialog and can affect which files are displayed in the dialog.

    Declaration

    Swift

    enum NSSaveOperationType : UInt { case SaveOperation case SaveAsOperation case SaveToOperation case AutosaveInPlaceOperation case AutosaveElsewhereOperation case AutosaveAsOperation }

    Objective-C

    typedef enum NSSaveOperationType : NSUInteger { NSSaveOperation = 0, NSSaveAsOperation = 1, NSSaveToOperation = 2, NSAutosaveElsewhereOperation = 3, NSAutosaveInPlaceOperation = 4, NSAutosaveAsOperation = 5 } NSSaveOperationType;

    Constants

    • SaveOperation

      NSSaveOperation

      A Save operation, which overwrites a document’s file or file package with the document’s contents.

      Available in OS X v10.0 and later.

    • SaveAsOperation

      NSSaveAsOperation

      A Save As operation, which writes a document’s contents to a new file or file package and then changes the document’s current location to point to the just-written file or file package.

      Available in OS X v10.0 and later.

    • SaveToOperation

      NSSaveToOperation

      A Save To operation, which writes a document’s contents to a new file or file package without changing the document’s current location to point to the new file or package.

      Available in OS X v10.0 and later.

    • AutosaveElsewhereOperation

      NSAutosaveElsewhereOperation

      An Autosave Elsewhere operation, which writes a document’s contents to a file or file package that is separate from the document’s current location, without changing the document’s current location.

      For an NSDocument subclass that overrides autosavesInPlace to have the value YEStrue, this is used during autosaving of documents that have never been saved and therefore do not yet have a document file that can be overwritten during autosaving. NSDocument may also pass NSAutosaveElsewhereOperation when invoking writeSafelyToURL:ofType:forSaveOperation:error: while duplicating or reverting a document.

      Available in OS X v10.7 and later.

    • AutosaveInPlaceOperation

      NSAutosaveInPlaceOperation

      An Autosave In Place operation, which overwrites a document’s file or file package with the document’s current contents even though the user has not explicitly requested it.

      Available in OS X v10.7 and later.

    • AutosaveAsOperation

      NSAutosaveAsOperation

      An Autosave As operation, which writes a document’s contents to a new file or file package even though the user has not explicitly requested it, then changes the document’s current location to point to the just-written file or file package.

      Available in OS X v10.8 and later.

    • NSAutosaveOperation

      NSAutosaveOperation

      Old name for the NSAutosaveElsewhereOperation operation type.

      Deprecated in OS X v10.7. Use NSAutosaveElsewhereOperation instead.

      Available in OS X v10.4 and later.

      Deprecated in OS X v10.7.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.0 and later.

  • When NSUbiquitousDocumentUserActivityType is present in a CFBundleDocumentTypes entry, AppKit automatically creates an NSUserActivity object for documents in iCloud, using the given activity type. The associated document’s URL is placed in the NSUserActivity object’s userInfo dictionary under this key.

    Declaration

    Swift

    let NSUserActivityDocumentURLKey: String

    Objective-C

    NSString * const NSUserActivityDocumentURLKey

    Constants

    • NSUserActivityDocumentURLKey

      NSUserActivityDocumentURLKey

      Key in the NSUserActivity object’s userInfo dictionary. Its value is the URL of the document associated with the user activity.

      Available in OS X v10.10 and later.