Class

NSDocument

The NSDocument abstract class defines the interface for macOS 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.

Overview

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 NSDocument​Controller and NSWindow​Controller).

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 macOS. It is important that overrides of write(to:​of​Type:​) and write(to:​of​Type:​for:​original​Contents​URL:​) 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 file​URL.

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 save​To​URL:​of​Type:​for​Save​Operation:​error:​ method that is meant always to be invoked during document saving, sets the file​Modification​Date property with the file’s new modification date after it has been written (for save​Operation and save​As​Operation 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 revert(to​Contents​Of:​of​Type:​) method that is meant always to be invoked during rereading of an open document, sets the file​Modification​Date 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 macOS 10.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 can​Concurrently​Read​Documents(of​Type:​) class method and return true for the appropriate document types. If specific document types rely on shared state information, however, you should return false for those types.

Symbols

Initializing

init()

Initializes and returns an empty NSDocument object.

init(contents​Of:​ URL, of​Type:​ String)

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

init(for:​ URL?, with​Contents​Of:​ URL, of​Type:​ String)

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

init(type:​ String)

Initializes a document of a specified type.

Loading Document Data

func data(of​Type:​ String)

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

func file​Wrapper(of​Type:​ String)

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

func read(from:​ Data, of​Type:​ String)

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

var is​Entire​File​Loaded:​ Bool

A Boolean value indicating whether the document’s file is completely loaded into memory.

Creating and Managing Window Controllers

func make​Window​Controllers()

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

var window​Nib​Name:​ String?

The name of the document’s sole nib file.

func window​Controller​Did​Load​Nib(NSWindow​Controller)

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

func window​Controller​Will​Load​Nib(NSWindow​Controller)

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

var window​Controllers:​ [NSWindow​Controller]

The document’s current window controllers.

func add​Window​Controller(NSWindow​Controller)

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

func remove​Window​Controller(NSWindow​Controller)

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

func should​Close​Window​Controller(NSWindow​Controller, delegate:​ Any?, should​Close:​ Selector?, context​Info:​ Unsafe​Mutable​Raw​Pointer?)

Invokes should​Close​Selector with the result of can​Close(with​Delegate:​should​Close:​context​Info:​) if the the specified window controller that is closing is the last one or is marked as causing the document to close.

Managing Document Windows

func show​Windows()

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

func set​Window(NSWindow?)

Sets the window Interface Builder outlet of this class.

var window​For​Sheet:​ NSWindow?

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

var display​Name:​ String!

The name of the document as displayed in the title bars of the document’s windows and in alert dialogs related to the document.

func default​Draft​Name()

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

Reading From and Writing to Files

func read(from:​ File​Wrapper, of​Type:​ String)

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

var file​Modification​Date:​ Date?

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

var should​Run​Save​Panel​With​Accessory​View:​ Bool

A Boolean value indicating whether the document’s Save panel displays a list of supported writable document types.

var keep​Backup​File:​ Bool

A Boolean value indicating whether the document keeps the backup files created before the document data is written to a file.

var backup​File​URL:​ URL?

The URL for the document’s backup file that was created during an autosave operation.

var file​URL:​ URL?

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

var is​Draft:​ Bool

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

Reading From and Writing to URLs

func read(from:​ URL, of​Type:​ String)

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

func write(to:​ URL, of​Type:​ String)

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

func write​Safely(to:​ URL, of​Type:​ String, for:​ NSSave​Operation​Type)

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

func write(to:​ URL, of​Type:​ String, for:​ NSSave​Operation​Type, original​Contents​URL:​ URL?)

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

func file​Attributes​To​Write(to:​ URL, of​Type:​ String, for:​ NSSave​Operation​Type, original​Contents​URL:​ URL?)

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.

func save(to:​ URL, of​Type:​ String, for:​ NSSave​Operation​Type, delegate:​ Any?, did​Save:​ Selector?, context​Info:​ Unsafe​Mutable​Raw​Pointer?)

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.

func can​Asynchronously​Write(to:​ URL, of​Type:​ String, for:​ NSSave​Operation​Type)

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.

func change​Count​Token(for:​ NSSave​Operation​Type)

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

func save(to:​ URL, of​Type:​ String, for:​ NSSave​Operation​Type, completion​Handler:​ (Error?) -> Void)

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.

func update​Change​Count(with​Token:​ Any, for:​ NSSave​Operation​Type)

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

func unblock​User​Interaction()

Unblocks the main thread during asynchronous saving.

Serialization

func continue​Activity(() -> Void)

Invokes the passed-in block to avoid a deadlock if perform​Activity(with​Synchronous​Waiting:​using:​) is being invoked recursively.

func continue​Asynchronous​Work​On​Main​Thread(() -> Void)

Invokes the passed-in block on the main thread.

func perform​Activity(with​Synchronous​Waiting:​ Bool, using:​ (() -> Void) -> Void)

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

func perform​Asynchronous​File​Access((() -> Void) -> Void)

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

func perform​Synchronous​File​Access(() -> Void)

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

Autosaving

func check​Autosaving​Safety()

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

func schedule​Autosaving()

Schedules periodic autosaving for the purpose of crash protection.

var has​Unautosaved​Changes:​ Bool

A Boolean value indicating whether the document has changes that have not been autosaved.

func autosave(with​Implicit​Cancellability:​ Bool, completion​Handler:​ (Error?) -> Void)

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

class func autosaves​In​Place()

Returns whether the receiver supports autosaving in place.

class func autosaves​Drafts()

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

class func preserves​Versions()

Returns whether the receiving subclass of NSDocument supports Versions.

func browse​Versions(Any?)

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

var autosaving​File​Type:​ String?

Returns the document type that should be used for an autosave operation.

var autosaving​Is​Implicitly​Cancellable:​ Bool

A Boolean value indicating whether autosaving is happening now but could be safely cancelled.

var autosaved​Contents​File​URL:​ URL?

The location of the most recently autosaved document contents.

iCloud Document Storage

func move​To​Ubiquity​Container(Any?)

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

class func uses​Ubiquitous​Storage()

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

Handling Window Restoration

func encode​Restorable​State(with:​ NSCoder)

Saves the interface-related state of the document.

func restore​State(with:​ NSCoder)

Restores the interface-related state of the document.

class func restorable​State​Key​Paths()

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

func invalidate​Restorable​State()

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

func restore​Window(with​Identifier:​ String, state:​ NSCoder, completion​Handler:​ (NSWindow?, Error?) -> Void)

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

Supporting User Activities

var user​Activity:​ NSUser​Activity?

An object encapsulating a user activity supported by this document.

func restore​User​Activity​State(NSUser​Activity)

Restores the state needed to continue the given user activity.

func update​User​Activity​State(NSUser​Activity)

Updates the state of the given user activity.

Managing Document Status

var is​Document​Edited:​ Bool

A Boolean value indicating whether the document has changes that have not been saved.

var file​Name​Extension​Was​Hidden​In​Last​Run​Save​Panel:​ Bool

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.

var is​In​Viewing​Mode:​ Bool

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

Handling User Actions

func print(Any?)

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

func run​Page​Layout(Any?)

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

func revert​To​Saved(Any?)

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

func save(Any?)

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

func save​As(Any?)

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

func save​To(Any?)

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

Closing Documents

func can​Close(with​Delegate:​ Any, should​Close:​ Selector?, context​Info:​ Unsafe​Mutable​Raw​Pointer?)

If the receiver is not dirty, this method immediately calls the should​Close​Selector callback on the specified delegate with true.

func close()

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.

Reverting Documents

func revert(to​Contents​Of:​ URL, of​Type:​ String)

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.

Duplicating Documents

func duplicate()

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

func duplicate(Any?)

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

func duplicate(with​Delegate:​ Any?, did​Duplicate:​ Selector?, context​Info:​ Unsafe​Mutable​Raw​Pointer?)

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

Renaming Documents

func rename(Any?)

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

Moving Documents

func move(Any?)

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

func move(completion​Handler:​ ((Bool) -> Void)? = nil)

Moves the document to a user-selected location.

Locking Documents

func lock(Any?)

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

func unlock(Any?)

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

func lock(completion​Handler:​ ((Bool) -> Void)? = nil)

Prevents the user from making further changes to the document.

func lock(completion​Handler:​ ((Error?) -> Void)? = nil)

Prevents further modifications from being made to the file.

func unlock(completion​Handler:​ ((Bool) -> Void)? = nil)

Allows the user to make modifications to the document.

func unlock(completion​Handler:​ ((Error?) -> Void)? = nil)

Allows the user to make modifications to the file.

var is​Locked:​ Bool

A Boolean value indicating whether or not the file can be written to.

Printing Documents

var print​Info:​ NSPrint​Info

The printing information associated with the document.

func should​Change​Print​Info(NSPrint​Info)

Returns a Boolean value indicating whether the receiver should allow changes to the default NSPrint​Info object used in printing the document.

func print​Operation(with​Settings:​ [String :​ Any])

Creates a print operation and returns it if successful.

var pdf​Print​Operation:​ NSPrint​Operation

A print operation that you can use to create a PDF representation of the document’s current contents.

func save​To​PDF(Any?)

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

Handling Errors

func present​Error(Error)

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

func will​Present​Error(Error)

Called when the receiver is about to present an error.

func will​Not​Present​Error(Error)

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.

Working with Undo Manager

var has​Undo​Manager:​ Bool

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

var undo​Manager:​ Undo​Manager?

The document’s undo manager object.

func update​Change​Count(NSDocument​Change​Type)

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

Managing File Types

var file​Type:​ String?

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

var file​Type​From​Last​Run​Save​Panel:​ String?

The file type that was last selected in the Save panel.

class func is​Native​Type(String)

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

class func readable​Types()

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

class func can​Concurrently​Read​Documents(of​Type:​ String)

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

class func writable​Types()

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

func writable​Types(for:​ NSSave​Operation​Type)

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

func file​Name​Extension(for​Type:​ String, save​Operation:​ NSSave​Operation​Type)

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

Validating User Interface Items

func validate​User​Interface​Item(NSValidated​User​Interface​Item)

Validates the specified user interface item that the receiver manages.

Scripting

func handle​Close(NSClose​Command)

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

func handle​Print(NSScript​Command)

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

func handle​Save(NSScript​Command)

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

var object​Specifier:​ NSScript​Object​Specifier

Returns an object specifier for the document.

var last​Component​Of​File​Name:​ String

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

Constants

NSSave​Operation​Type

A save operation type specifies the type of document save operation to perform. These values are used with method parameters of type NSSave​Operation​Type. 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.

NSDocument​Change​Type

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 update​Change​Count(_:​) method.

Document URL User Activity Key

When NSUbiquitous​Document​User​Activity​Type is present in a CFBundle​Document​Types entry, AppKit automatically creates an NSUser​Activity object for documents in iCloud, using the given activity type. The associated document’s URL is placed in the NSUser​Activity object’s user​Info dictionary under this key.