Next Page > Hide TOC

Legacy Documentclose button

Important: The information in this document is obsolete and should not be used for new development.

NSDocument

Inherits from
Package
com.apple.cocoa.application
Companion guide

Class at a Glance

NSDocument is an abstract class that defines the interface for documents, objects that can internally represent data displayed in windows and that can read data from and write data to files. 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.

Principal Attributes

Commonly Used Methods

dataOfType

Returns the document’s data in a specified type.

readFromDataOfType

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

writeToFile

Writes the document’s data to a file.

writeToURLOfType

Writes the document’s data to a URL.

readFromURLOfType

Reads the document’s data from a file.

windowNibName

Returns the name of the document’s sole nib file (resulting in the creation of a window controller for the window in that file).

makeWindowControllers

Creates and returns the window controllers used to manage document windows.

Overview

NSDocument is an abstract class that defines the interface for documents. In a functional sense, a document is a repeatable container for a unique body of information identified by a name under which it is stored. In the context of the Application Kit, a document is an instance of an NSDocument subclass that knows how to represent internally, in one or more formats, the persistent data displayed in windows. A document can read that data from files and write it to files. It is also the first-responder target for many menu commands related to documents, such as Save Document, Revert Document, and Print Document. (When going up the responder chain, the Application Kit queries a window’s NSDocument, if it exists, just after it queries the window delegate, if that is different from the NSDocument.) 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 Application Kit classes that establish an architectural basis for document-based applications (the others being NSDocumentController and NSWindowController).

To create a useful NSDocument subclass, you must override some primitive methods and might want to 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 primitive methods, subclasses must add the knowledge of particular types and how data of the document’s native type is structured internally and represented in document windows. Subclasses are also responsible for the creation of the window controllers that manage document windows and for the implementation of undo and redo. NSDocument takes care of much of the rest, including running Open and Save panels and generally managing the state of the document. See “Creating a Subclass of NSDocument” for more on creating subclasses of NSDocument, particularly the list of primitive methods that subclasses must override and those that may be overridden.

Writing of HFS Creator and File Type Codes

The fileAttributesToWriteToFile method can be overridden to specify that a creator code and/or file type code should be written to a file as it is being saved. See NSPathUtilities for descriptions of the new FileHFSCreatorCode and FileHFSTypeCode file attributes. NSDocument’s implementation of fileAttributesToWriteToFile returns zeroed-out creator and file type codes, effectively excluding creator code and file type code from the attribute preservation described in fileAttributesToWriteToFile.

NSDocument Saving Behavior

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

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 Mac OS X. It is important that overrides of writeToFile make no assumptions about the file paths passed as parameters, including:

Tasks

Constructors

Initializing an NSDocument

Loading and Representing Document Data

Creating and Managing Window Controllers

Managing Document Windows

Reading from and Writing to Files

Reading from and Writing to URLs

Autosaving

Managing Document Status

Responding to User Actions

Closing Documents

Reverting Documents

Printing Documents

Handling Errors

Working with Undo Manager

Managing File Types

Managing Menu Commands

Deprecated Methods

Constructors

NSDocument

Creates an empty NSDocument object.

public NSDocument()

Creates an NSDocument object of document type docType containing data stored in the file fileName.

public NSDocument(String fileName, String docType)

Discussion

If the file cannot be opened, displays an alert dialog informing the user and then returns null. In opening the file, invokes the readFromFile method. If the document successfully opens the file, it calls setFileName and setFileType with fileName and docType, respectively, as arguments.

Creates an NSDocument of document type docType containing data stored at aURL.

public NSDocument(java.net.URL aURL, String docType)

Discussion

If the location cannot be opened, displays an alert dialog informing the user and then returns null. In opening the location, invokes the readFromURL method. If the document successfully opens the file, it calls setFileName and setFileType with fileName and docType, respectively, as arguments.

Static Methods

isNativeType

Returns whether document data of type aType is a native type—one the receiver can both read and write.

public static boolean isNativeType(String aType)

See Also

readableTypes

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

public static NSArray readableTypes()

See Also

writableTypes

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

public static NSArray writableTypes()

See Also

Instance Methods

addWindowController

Adds the window controller aController to the list of window controllers associated with the receiver.

public void addWindowController(NSWindowController aController)

Discussion

An NSDocument uses this list when it displays all document windows, sets window edited status upon an undo or redo operation, and modifies window titles. The method also sets the document outlet of the window controller to this if it is not already set. 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 response to a user event, you should invoke this method for each created window controller. To remove a window controller from the list of active controllers, send it NSWindowController’s close message.

See Also

autosavedContentsFileURL

Returns the location of the most recently autosaved document contents.

public URL autosavedContentsFileURL()

Discussion

The default implementation of this method just returns whatever was stored by a previous invocation of the default implementation of setAutosavedContentsFileURL.

Availability
See Also

autosaveDocument

Autosaves the document’s contents at an appropriate location.

public void autosaveDocument(Object delegate, NSSelector didAutosaveSelector, Object contextInfo)

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:

public void documentDidAutosave (NSDocument document, boolean didAutosaveSuccessfully,  Object contextInfo)

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

Availability
See Also

autosavingFileType

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

public String autosavingFileType()

Discussion

The default implementation just returns [self fileType]. You can override this method and return null in your override to completely disable autosaving of individual documents. You can also override it if your application defines a document type that is specifically designed for autosaving, for example, one that efficiently represents document content changes instead of complete document contents.

Availability

canCloseDocument

This method is no longer supported.

public boolean canCloseDocument()

Discussion

Instead use the three parameter version of this method.

If the receiver is not dirty, this method will immediately call the shouldCloseSelector callback on delegate with true.

public void canCloseDocument(Object delegate, NSSelector shouldCloseSelector, Object contextInfo)

Discussion

If the receiver is dirty, an alert will be presented giving the user a chance to save, not save, or cancel. If the user chooses to save, this method will save the document. If the save completes successfully, this method will call the callback with true. If the save is canceled or otherwise unsuccessful, this method will call the callback with false. This method may be called by shouldCloseWindowController. It is also called by NSDocumentController’s closeAllDocuments. You should call it before you call close if you are closing the document and want to give the user a chance save any edits. Pass the contextInfo object with the callback.

The shouldCloseSelector callback method should have the following signature:

public void documentShouldClose (NSDocument doc, boolean shouldClose,  Object  contextInfo)
Availability

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.

public 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. Specifically, this method is not called when a user quits an application. Additional information on application termination can be found in Graceful Application Termination.

See Also

dataOfType

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

public NSData dataOfType(String typeName)

Discussion

The typeName argument specifies the document type. If the data object cannot be created, returns null. The default implementation of this method throws an exception because at least one of the writing methods (this method, writeToURLOfType, or fileWrapperOfType) must be overridden.

Availability
See Also

dataRepresentationOfType

public NSData dataRepresentationOfType(String aType)

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 throws an InternalInconsistencyException. 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.

Availability
See Also

displayName

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

public String 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.

fileAttributesToWriteToFile

public NSDictionary fileAttributesToWriteToFile(String fullDocumentPath, String docType, int 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 NSPathUtilities class.

Availability

fileAttributesToWriteToURLOfType

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.

public NSDictionary fileAttributesToWriteToURLOfType(URL absoluteURL, String typeName, int saveOperation, URL absoluteOriginalContentsURL)

Discussion

If not successful, returns null.The set of valid file attributes is a subset of those understood by the NSPathUtilities class. The default implementation of this method returns a dictionary with FileHFSCreatorCode and FileHFSTypeCode entries that have a value of 0 for SaveOperation, or a dictionary with an appropriate FileExtensionHidden entry for SaveAsOperation and SaveToOperation. You can override this method to customize the attributes that are written to document files.

This method is meant to be used just for attributes that need to be written for the first time, for SaveAsOperation and SaveToOperation.

Invokers of this method should silently ignore invalid attributes. Of particular interest is the FileExtensionHidden attribute, which is documented in NSPathUtilities.

The dictionary returned by the default implementation of this method contains an FileExtensionHidden entry when that is appropriate. 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.

An override of writeSafelyToURLOfType should invoke this method and set the returned attributes on the written document file.

Implementers of overrides of this method should not assume that:

Availability

fileModificationDate

Returns the last known modification date of the document's on-disk representation.

public NSDate fileModificationDate()

Discussion

NSDocument's 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 application.

Availability
See Also

fileName

public String fileName()

Discussion

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

Availability
See Also

fileNameExtensionWasHiddenInLastRunSavePanel

Returns true if a Save panel has been presented by this document, and the user chose to hide the name extension of the file that was selected in that Save panel.

public boolean fileNameExtensionWasHiddenInLastRunSavePanel()

Discussion

Returns false otherwise.

fileNameFromRunningSavePanelForSaveOperation

public String fileNameFromRunningSavePanelForSaveOperation(int saveOperation)

Discussion

Runs the modal Save panel and returns the filename (as a fully qualified path) selected for the receiver. saveOperation determines the title of the Save panel (Save, Save As, Save To). It also affects whether the Save panel includes an accessory view with a pop-up list containing the document’s native or writable types. If saveOperation is SaveOperation or SaveAsOperation, the accessory pop-up list contains only those document types the application can read and write. If saveOperation is SaveToOperation, the pop-up list additionally includes the document types that the application can write (but can’t read). If there is only one type the document can be written to, or if shouldRunSavePanelWithAccessoryView returns false, the accessory view isn’t shown. The default extension for saved documents is the first extension assigned for the document’s native type or, if there is no native type, the extension for the first writable type specified in the CFBundleDocumentTypes property. File packages are treated as files.

Availability
See Also

fileType

Returns the document type under which the receiver is saved.

public String fileType()

Discussion

When a document is saved, the type is determined by the file extension, as defined in the custom info dictionary (specified in Info.plist).

See Also

fileTypeFromLastRunSavePanel

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

public String 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.

fileURL

Returns the location of the document's on-disk representation.

public URL fileURL()

Discussion

The default implementation of this method returns whatever was stored by a previous invocation of the default implementation of setFileURL.For backward binary compatibility with Mac OS X v10.3 and earlier, if fileName is overridden, the default implementation of this method instead invokes [self fileName] and returns the result as a URL.

Availability
See Also

fileWrapperOfType

Creates and returns a file wrapper that contains the contents of the document.

public NSFileWrapper fileWrapperOfType(String typeName)

Discussion

The document is formatted to a specified type typeName. If unsuccessful, the default implementation of this method returns null.

Availability
See Also

fileWrapperRepresentationOfType

public NSFileWrapper fileWrapperRepresentationOfType(String aType)

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.

Availability
See Also

hasUnautosavedChanges

Return true if the document has changes that have not been autosaved, false otherwise, as determined by the history of previous invocations of updateChangeCount.

public boolean hasUnautosavedChanges()

Availability

hasUndoManager

Returns whether the receiver owns or should own an NSUndoManager.

public boolean hasUndoManager()

See Also

initForURLWithContentsOfURLOfType

Initializes a document located by a URL.

public boolean initForURLWithContentsOfURLOfType(URL absoluteDocumentURL, URL absoluteDocumentContentsURL, String typeName)

Discussion

Initializes the document located by absoluteDocumentURL, of the specified type typeName, but by reading the contents for the document from absoluteDocumentContentsURL, and returns it if successful. If not successful, returns null.

The absoluteDocumentURL argument is null 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 constant to indicate that an autosaved document is being reopened:

ChangeReadOtherContents

Availability

initWithContentsOfURLOfType

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

public boolean initWithContentsOfURLOfType(URL absoluteURL, String typeName)

Discussion

The URL is specified by absoluteURL, and the type is specified by typeName. Returns the document if successful. If not successful, returns null. You can override this method to customize the reopening of autosaved documents.

This method is invoked by the NSDocumentController method makeDocumentWithContentsOfURLOfType. The default implementation of this method invokes readFromURLOfType, setFileURL, setFileType, and setFileModificationDate.

For backward binary compatibility with Mac OS v10.3 and earlier, the default implementation of this method instead another method if it is overridden and the URL uses the file: scheme. It still invokes setFileModificationDate in this situation.

Availability

initWithType

Initializes a document of a specified type, and returns it if successful.

public boolean initializeWithType(String typeName)

Discussion

The type is specified by typeName. If not successful, returns null.

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 to initialize NSDocument's private instance variables.

Availability

isDocumentEdited

Returns true if the receiver has been edited since it was last saved or if the document is new; otherwise, returns false.

public boolean isDocumentEdited()

Discussion

The edited status of each document window reflects the document’s edited status.

See Also

keepBackupFile

Returns whether the receiver should keep the backup files created before document data is written to a file (false by default).

public boolean keepBackupFile()

Discussion

Override this method if you want different behavior.

See Also

lastError

Returns the NSError object that was most recently set.

public NSError lastError()

Discussion

Errors are set by NSDocument Java member functions or overrides using the setLastError member function. Typically, this member function is called only by the Application Kit itself.

Availability
See Also

loadDataRepresentation

This method has been deprecated.

public boolean loadDataRepresentation(NSData docData, String docType)

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 after an NSData object is created from the contents of the file wrapper (which can include directories). The default implementation throws an InternalInconsistencyException. Subclasses must override this method unless they override readFromFile or loadFileWrapperRepresentation 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.

Availability
See Also

loadFileWrapperRepresentation

This method has been deprecated.

public boolean loadFileWrapperRepresentation(NSFileWrapper wrapper, String docType)

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 to load the data. If wrapper is a directory, it returns false by default; subclasses can override to handle file wrappers that are directories. This method is typically invoked by readFromFile after it creates an NSData object from the contents of the file.

Availability
See Also

makeWindowControllers

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

public void makeWindowControllers()

Discussion

The base class implementation creates an NSWindowController 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 NSDocumentController’s open... methods, but you might want to call it directly in some circumstances.

See Also

preparePageLayout

Invoked by runModalPageLayoutWithPrintInfo and runModalPageLayout to do any customization of the Page Layout panel pageLayout, such as adding an accessory view.

public boolean preparePageLayout(NSPageLayout pageLayout)

Discussion

Returns true if successfully prepared, and false otherwise. The default implementation is empty and returns true.

prepareSavePanel

Invoked by runModalSavePanel to do any customization of the Save panel savePanel.

public boolean prepareSavePanel(NSSavePanel savePanel)

Discussion

Returns true if successfully prepared, and false otherwise. The default implementation is empty and returns true.

presentError

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

public boolean presentError(NSError error)

Discussion

Returns true if error recovery was done, false otherwise. This method does not return until the user dismisses the alert.

NSDocument’s 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 subclassers an opportunity to customize error presentation. You should not override this method but should instead override willPresentError.

Availability
See Also

presentErrorModalForWindow

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

public void presentErrorModalForWindow(NSError error, NSWindow window, Object delegate, NSSelector didPresentSelector, Object contextInfo)

Discussion

When the user dismisses the alert and any recovery possible for the error and chosen by the user has been attempted, sends the message didPresentSelector to the specified delegate. The method selected by didPresentSelector must have the same signature as:

public void didPresentErrorWithRecovery (boolean didRecover, Object  contextInfo)

NSDocument’s 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 implementations of several NSDocument methods invoke this method.

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

Availability
See Also

printDocument

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

public void printDocument(Object sender)

Discussion

An NSDocument receives this action message as it travels up the responder chain. The default implementation invokes printShowingPrintPanel with an argument of true.

See Also

printDocumentWithSettings

Prints the document.

public void printDocumentWithSettings(NSDictionary printSettings, boolean showPrintPanel, Object delegate, NSSelector didPrintSelector, Object contextInfo)

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

public void documentDidPrint (NSDocument document, boolean didPrintSuccessfully,  Object  contextInfo)

The default implementation of this method invokes printOperationWithSettings. If null is returned it presents the error to the user in a document-modal panel before messaging the delegate..

For backward binary compatibility with Mac 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.

Availability
See Also

printInfo

Returns the receiver’s customized NSPrintInfo object or the default NSPrintInfo instance.

public NSPrintInfo printInfo()

Discussion

The document’s copy of the NSPrintInfo object can either be directly set or set as a result of running the Page Layout panel. A subclass can override this method to always return the shared NSPrintInfo instance if it does not want its own copy.

See Also

printOperationWithSettings

Creates a print operation and returns it if successful.

public NSPrintOperation printOperationWithSettings(NSDictionary printSettings)

Discussion

If not successful, returns null. 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. The default implementation of this method does nothing. You must override it to enable printing in your application.

Availability
See Also

printShowingPrintPanel

This method has been deprecated.

public void printShowingPrintPanel(boolean flag)

Discussion

Overridden by subclasses to print the current document’s (the receiver’s) data; if flag is true, the implementation should first display the Print panel. This method is typically invoked by printDocument with an argument of true. 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.

Availability
See Also

readFromDataOfType

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

public boolean readFromDataOfType(NSData data, String typeName)

Discussion

The type is specified by typeName. If not successful, the method returns false. The default implementation of this method throws an exception because at least one of the three reading methods (this method, readFromURLOfType, readFromFileWrapperOfType), or every method that may invoke readFromURLOfType, must be overridden.

Availability

readFromFile

This method has been deprecated.

public boolean readFromFile(String fileName, String docType)

Discussion

Reads and loads document data of type docType from the file fileName, returning whether the operation was successful. This method invokes loadDataRepresentation and is invoked when the receiver is first created and initialized.

This method is one of the location-based primitives. Subclasses can override this method instead of overriding loadDataRepresentation 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’s or other filtering services.

Availability
See Also

readFromFileWrapperOfType

Set the contents of this document by reading from a file wrapper of a specified type, and return true if successful.

public boolean readFromFileWrapperOfType(NSFileWrapper fileWrapper, StringtypeName)

Discussion

If not successful, return false.

Availability
See Also

readFromURL

This method has been deprecated.

public boolean readFromURL(java.net.URL aURL, String docType)

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.

Availability

readFromURLOfType

Sets the contents of this document by reading from a file or file package located by a URL, of a specified type, and returns true if successful.

public boolean readFromURLOfType(URL absoluteURL, String typeName)

Discussion

The URL is represented by absoluteURL, and the document type by typeName. If not successful, returns false.

Availability
See Also

removeWindowController

Removes windowController from the receiver.

public void removeWindowController(NSWindowController windowController)

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.

See Also

revertDocumentToSaved

The action of the File menu item Revert to Saved in a document-based application.

public void revertDocumentToSaved(Object sender)

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 revertToContentsOfURLOfType. If that returns false, the method presents the error to the user in an document-modal alert dialog.

See Also

revertToContentsOfURLOfType

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 and returns true if successful.

public boolean revertToContentsOfURLOfType(URL absoluteURL, String typeName)

Discussion

The URL is represented by absoluteURL, and the document type by typeName. If not successful, returns false.

Availability

revertToSavedFromFile

This method has been deprecated.

public boolean revertToSavedFromFile(String fileName, String type)

Discussion

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

Availability
See Also

revertToSavedFromURL

This method has been deprecated.

public boolean revertToSavedFromURL(java.net.URL aURL, String type)

Discussion

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

Availability
See Also

runModalPageLayout

Runs the modal page layout panel with the receiver’s printing information object (printInfo).

public void runModalPageLayout(NSPrintInfo printInfo, Object delegate, NSSelector didRunSelector, Object contextInfo)

Discussion

Invoked from the action method runPageLayout. The contextInfo argument provides any additional context information. Presents the page layout panel application 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:

public void documentDidRunModalPageLayout (NSDocument document,  boolean accepted, void  contextInfo)

runModalPageLayoutWithPrintInfo

This method has been deprecated. Use runModalPageLayout instead.

public int 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 runModalPageLayout instead.

Availability
See Also

runModalPrintOperation

Runs a print operation printOperation modally.

public void runModalPrintOperation(NSPrintOperation printOperation, Object delegate, NSSelector didRunSelector, Object contextInfo)

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:

public void documentDidRunModalPrintOperation(NSDocument document,  boolean success, void  contextInfo)

runModalSavePanel

Runs the modal Save panel savePanel with accessory view accessoryView and returns the result constant (indicating the button clicked by the user).

public int runModalSavePanel(NSSavePanel savePanel, NSView accessoryView)

Discussion

accessoryView is usually a pop-up list containing the receiver’s native types and its supported writable types. Invoked by fileNameFromRunningSavePanelForSaveOperation.

This method is no longer supported.

Prepares and runs the modal Save panel.

public void runModalSavePanel(int saveOperation, Object delegate, NSSelector didSaveSelector, Object contextInfo)

Discussion

Invoked from saveDocument, and the action methods saveDocumentAs and saveDocumentTo. Calls prepareSavePanel to allow further customization of the Save panel. The delegate is assigned to the Save panel. Pass the contextInfo object with the callback.

The didSaveSelector callback method should have the following signature:

public void documentDidSave (NSDocument doc, boolean didSave, Object  contextInfo)
Availability
See Also

runPageLayout

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

public void runPageLayout(Object sender)

Discussion

The default implementation invokes runModalPageLayout 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.

See Also

saveDocument

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

public void saveDocument(Object sender)

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.

See Also

Runs the Save panel and invokes saveToFile with the result.

public void saveDocument(Object delegate, NSSelector didSaveSelector, Object contextInfo)

Discussion

It is called from the saveDocument action method and from canCloseDocument if the user chooses to save. Pass the contextInfo object with the callback. The delegate is assigned to the Save panel.

The didSaveSelector callback method should have the following signature:

public void documentDidSave (NSDocument doc, boolean didSave, Object  contextInfo)

saveDocumentAs

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

public void saveDocumentAs(Object sender)

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.

See Also

saveDocumentTo

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

public void saveDocumentTo(Object sender)

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.

See Also

saveToFile

This method has been deprecated.

public void saveToFile(String fileName, int saveOperation, Object delegate, NSSelector didSaveSelector, Object contextInfo)

Discussion

Called after the user has been given the opportunity to select a destination through the modal Save panel presented by runModalSavePanel. The delegate is assigned to the Save panel. If fileName is non-null, 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 true if the document is saved successfully, and false otherwise. The saveOperation is one of the constants in “Constants.” Pass contextInfo with the callback.

The didSaveSelector callback method should have the following signature:

public void documentDidSave (NSDocument doc, boolean didSave, Object  contextInfo)
Availability

saveToURLOfType

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 true if successful.

public boolean saveToURLOfType(URL absoluteURL, String typeName, int saveOperation)

Discussion

The URL is represented by absoluteURL, the document type by typeName, and the save operation type by saveOperation. If not successful, returns false.

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.

public void saveToURLOfType(URL absoluteURL, String typeName, int saveOperation, Object delegate, NSSelector didSaveSelector, Object contextInfo)

Discussion

The URL is represented by absoluteURL,, the document type by typeName, and the save operation type by saveOperation. 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:

public void documentDidSave (NSDocument document, boolean didSaveSuccessfully,  Object  contextInfo)
Availability

setAutosavedContentsFileURL

Sets the location of the most recently autosaved document contents.

public void setAutosavedContentsFileURL(URL absoluteURL)

Discussion

The default implementation of this method records the URL and notifies the shared document controller that this document should be autoreopened if the application quits or crashes before the document is saved.

Availability
See Also

setFileModificationDate

Sets the last known modification date of the document's on-disk representation to modificationDate.

public void setFileModificationDate(NSDate modificationDate)

Discussion

NSDocument's 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 application.

Availability
See Also

setFileName

This method has been deprecated.

public void setFileName(String 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.

Availability
See Also

setFileType

Sets the document type under which the file is saved to docType.

public void setFileType(String docType)

Discussion

The document type affects how the data is filtered when it is written to or read from a file.

See Also

setFileURL

Sets the location of the document's on-disk representation.

public void setFileURL(URL absoluteURL)

Discussion

This method doesn't actually rename the document; it's just for recording the document's location during initial opening or saving. The default implementation of this method just records the URL so that the default implementation of fileURL can return it.

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

Availability
See Also

setHasUndoManager

Sets whether the receiver has its own NSUndoManager.

public void setHasUndoManager(boolean flag)

Discussion

If flag is false and the receiver currently owns an NSUndoManager, the NSUndoManager is released after being removed as an observer of undo-related notifications.

See Also

setLastError

Sets the NSError object that will be returned by the lastError member function.

public void setLastError(NSError inError)

Discussion

The inError parameter represents the NSError object to be set.

Whenever your application’s override of an NSDocument member function detects failure and is going to return null or whatever signals failure for that particular function, it should first call this function and pass in an NSError object that encapsulates the reason for the failure. However, it needn’t do so if it’s going to signal failure because it called a member function that itself failed and is expected to have already called setLastError.

Availability
See Also

setPrintInfo

Sets the receiver’s NSPrintInfo object to printInfo; this object is used in laying out the document for printing.

public void setPrintInfo(NSPrintInfo printInfo)

See Also

setUndoManager

Sets the undo manager owned by the receiver to undoManager and releases any undo manager currently owned by the receiver.

public void setUndoManager(NSUndoManager undoManager)

Discussion

If undoManager is null, it turns off the hasUndoManager flag. If undoManager is non-null, it adds the receiver as an observer of NSUndoManager.DidUndoChangeNotification, NSUndoManager.DidRedoChangeNotification, and NSUndoManager.WillCloseUndoGroupNotification.

See Also

setWindow

Sets the window Interface Builder outlet of this class.

public void setWindow(NSWindow aWindow)

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.

shouldChangePrintInfo

Returns whether the receiver should allow changes to the default NSPrintInfo object newPrintInfo used in printing the document.

public boolean shouldChangePrintInfo(NSPrintInfo newPrintInfo)

Discussion

The default implementation returns true. Subclasses can override this method to return false. This method is invoked by the runPageLayout method, which sets a new NSPrintInfo for the document only if this method returns true.

shouldCloseWindowController

This method variant is no longer supported. Instead use the other variant of this method.

public boolean shouldCloseWindowController(NSWindowController windowController)

Discussion

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

Availability

Invokes shouldCloseSelector with the result of canCloseDocument if the windowController that is closing is the last one or is marked as causing the document to close.

public void shouldCloseWindowController(NSWindowController windowController, Object delegate, NSSelector shouldCloseSelector, Object contextInfo)

Discussion

Otherwise it invokes shouldCloseSelector with true. 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 asking its delegate windowShouldClose. Pass contextInfo with the callback.

The shouldCloseSelector callback method should have the following signature:

public void documentShouldClose (NSDocument document, boolean shouldClose,  Object  contextInfo)
See Also

shouldRunSavePanelWithAccessoryView

Returns true by default; as a result, when NSDocument displays the Save panel, it includes an accessory view containing a pop-up list of supported writable document types.

public boolean shouldRunSavePanelWithAccessoryView()

Discussion

Subclasses can override to return false, thus excluding the accessory view from the Save panel.

See Also

showWindows

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

public void showWindows()

undoManager

Returns the NSUndoManager used by the receiver or null if the receiver should not own one.

public NSUndoManager undoManager()

Discussion

If the undo manager doesn’t exist and hasUndoManager returns true, it creates one and invokes setUndoManager with the NSUndoManager as argument.

updateChangeCount

Updates the receiver’s change count according to changeType.

public void updateChangeCount(int changeType)

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. changeType is described in “Constants.” If you are implementing undo and redo in an application, 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 NSDocument’s 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.

validateMenuItem

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

public boolean validateMenuItem(NSMenuItem anItem)

Discussion

Returns true if anItem should be enabled, false otherwise. Returns true for Revert if the document has been edited and a file exists for the document. Returns true 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.

willPresentError

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

public NSError willPresentError(NSError error)

Discussion

The default implementation of this method merely returns the passed-in error. The returned error may simply be forwarded to the 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.

Availability
See Also

windowControllerDidLoadNib

Sent after windowController loads a nib file if the receiver is the nib file's owner.

public void windowControllerDidLoadNib(NSWindowController windowController)

Discussion

See the class description for NSWindowController for additional information about nib files and "File's Owner".

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 windowControllerDidLoadNib and do custom processing after the nib file is loaded.

The default implementation of this method does nothing.

See Also

windowControllers

Returns the receiver’s current window controllers.

public NSArray windowControllers()

Discussion

If there are no window controllers, returns an empty NSArray.

See Also

windowControllerWillLoadNib

Sent before windowController loads a nib file if the receiver is the nib file's owner.

public void windowControllerWillLoadNib(NSWindowController windowController)

Discussion

See the class description for NSWindowController for additional information about nib files and "File's Owner".

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.

See Also

windowForSheet

Returns the most appropriate window, of the windows associated with the receiver, to use as the parent window of a document-modal sheet.

public NSWindow windowForSheet()

Discussion

May return null, in which case the sender should present an application-modal panel. NSDocument's implementation of this method returns the window of the first window controller, or NSApplication.sharedApplication(). mainWindow() if there are no window controllers or if the first window controller has no window.

windowNibName

Overridden by subclasses to return the name of the document’s sole nib file.

public String 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 implementation returns null.

See Also

writableTypesForSaveOperation

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

public NSArray writableTypesForSaveOperation(int saveOperation)

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 application can play the Editor role. For NSSaveToOperation the returned array may include types for which the application can only play the Viewer role, and other types that the application can merely export. The default implementation of this method returns [[self class] writableTypes] with, except during NSSaveToOperations, types for which isNativeType returns false 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.

Availability

writeSafelyToURLOfType

Writes the contents of the document to a file or file package.

public boolean writeSafelyToURLOfType(URL absoluteURL, String typeName, int saveOperation)

Discussion

The file or file package is located by the URL absoluteURL, formatted to the specified type typeName, for a particular kind of save operation saveOperation. Returns true if successful. If not successful, returns false.

The default implementation of this method invokes fileAttributesToWriteToURLOfType 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 application crash, system crash, hardware failure, power outage, and so on. If you override this method, be sure to invoke the superclass implementation.

For SaveOperation, the default implementation of this method invokes keepBackupFile 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 Mac OS X v10.3 and earlier, the default implementation of this method instead invokes writeWithBackupToFile if that method is is overridden and the URL uses the file: scheme. The save operation in this case is never AutosaveOperation; SaveToOperation is used instead.

Availability
See Also

writeToFile

Writes document data of type docType to the file fileName, returning whether the operation was successful.

public boolean writeToFile(String fileName, String docType)

Discussion

This method invokes dataRepresentationOfType and is indirectly invoked whenever the document file is saved. It uses NSData’s writeToFile method 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’s filtering services.

See “NSDocument Saving Behavior” for additional information about saving documents.

See Also

This method is called from writeWithBackupToFile to actually write the file of type docType to fullDocumentPath.

public boolean writeToFile(String fullDocumentPath, String docType, String fullOriginalDocumentPath, int saveOperationType)

Discussion

fullOriginalDocumentPath is the path to the original file if there is one and null otherwise. The default implementation simply calls writeToFile with no arguments. 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 “NSDocument Saving Behavior” for additional information about saving documents.

writeToURL

public boolean writeToURL(java.net.URL aURL, String docType)

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.

writeToURLOfType

Writes the contents of the file to a file or file package located by a URL, formatted to a specified type, and returns true if successful.

public boolean writeToURLOfType(URL absoluteURL, String typeName)

Discussion

The URL is represented by absoluteURL and the document type by typeName. If not successful, the method returns false.

Writes 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 true if successful.

public boolean writeToURLOfType(URL absoluteURL, String typeName, int saveOperation, URL absoluteOriginalContentsURL)

Discussion

The URL is represented by absoluteURL, the document type by typeName, and the save operation type by saveOperation. If not successful, returns false.

You can override this method instead of one of the three simple writing methods (readFromURLOfType, readFromFileWrapperOfType, readFromDataOfType) 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 that returned by 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 that returned by – fileURL.

Availability
See Also

writeWithBackupToFile

This method has been deprecated.

public boolean writeWithBackupToFile(String fullDocumentPath, String docType, int 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 false. In between those two things, it calls writeToFile to write the document of type docType to fullDocumentPath. You should never need to call writeWithBackupToFile, 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.”

Availability

Constants

The following constants specify types of save operations. These values are used with method parameters, such as int saveOperation,. Depending on the method, those parameters can affect the title of the Save panel, as well as the files displayed.

Constant

Description

SaveOperation

Specifies a Save operation.

SaveAsOperation

Specifies a Save As operation.

SaveToOperation

Specifies a Save To operation.

AutosaveOperation

Specifies an autosave operation, writing a document’s contents to a file or file package separate from the document's current one.

Available in Mac OS X v10.4 and later.

Change counts indicate a document’s edit status. The following constants indicate how a document should operate on its change count and are used by updateChangeCount

Constant

Description

ChangeDone

Increment change count.

ChangeUndone

Decrement change count.

ChangeCleared

Set change count to 0.

ChangeReadOtherContents

Document was initialized with contents of file or file package other than the one whose location would be returned by fileURL.

Available in Mac OS X v10.4 and later.

ChangeAutosaved

Document's contents have been autosaved.

Available in Mac OS X v10.4 and later.



Next Page > Hide TOC


© 1997, 2007 Apple Inc. All Rights Reserved. (Last updated: 2007-02-01)


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.