| Inherits from | |
| Conforms to | |
| Framework | /System/Library/Frameworks/AppKit.framework |
| Availability | Available in Mac OS X v10.0 and later.
|
| Companion guide | |
| Declared in | NSDocument.h NSDocumentScripting.h |
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.
Window controllers
Filenames
Document types
Print information
initDesignated initializer for new documents
initWithContentsOfURL:ofType:error:For existing documents
dataOfType:error:Returns the document’s data in a specified type.
readFromData:ofType:error:Sets the contents of this document by reading from data of a specified type.
writeToURL:ofType:error:Writes the document’s data to a URL.
readFromURL:ofType:error:Reads the document’s data from a file.
windowNibNameReturns the name of the document’s sole nib file (resulting in the creation of a window controller for the window in that file).
makeWindowControllersCreates and returns the window controllers used to manage document windows.
NSDocument is an abstract class that defines the interface for documents.
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 the Application Kit, 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 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 methods, and you 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 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 “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.
The fileAttributesToWriteToFile:ofType:saveOperation: method can be overridden to specify that a creator code or file type code (or both) should be written to a file as it is being saved. See NSFileManager for descriptions of the NSFileHFSCreatorCode and NSFileHFSTypeCode file attributes. The NSDocument implementation of fileAttributesToWriteToFile:ofType:saveOperation: returns zeroed-out creator and file type codes, effectively excluding creator code and file type code from the attribute preservation described in fileAttributesToWriteToFile:ofType:saveOperation:.
NSDocument 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 Mac 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 return value of fileName.
– init
– initWithContentsOfURL:ofType:error:
– initForURL:withContentsOfURL:ofType:error:
– initWithType:error:
– makeWindowControllers
– windowNibName
– windowControllerDidLoadNib:
– windowControllerWillLoadNib:
– windowControllers
– addWindowController:
– removeWindowController:
– shouldCloseWindowController:delegate:shouldCloseSelector:contextInfo:
– readFromFileWrapper:ofType:error:
– fileModificationDate
– setFileModificationDate:
– runModalSavePanelForSaveOperation:delegate:didSaveSelector:contextInfo:
– shouldRunSavePanelWithAccessoryView
– keepBackupFile
– readFromURL:ofType:error:
– writeToURL:ofType:error:
– writeSafelyToURL:ofType:forSaveOperation:error:
– writeToURL:ofType:forSaveOperation:originalContentsURL:error:
– setFileURL:
– fileURL
– fileAttributesToWriteToURL:ofType:forSaveOperation:originalContentsURL:error:
– saveToURL:ofType:forSaveOperation:delegate:didSaveSelector:contextInfo:
– saveToURL:ofType:forSaveOperation:error:
– hasUnautosavedChanges
– autosaveDocumentWithDelegate:didAutosaveSelector:contextInfo:
– autosavingFileType
– setAutosavedContentsFileURL:
– autosavedContentsFileURL
– prepareSavePanel:
– printDocument:
– runPageLayout:
– revertDocumentToSaved:
– saveDocument:
– saveDocumentAs:
– saveDocumentTo:
– saveDocumentWithDelegate:didSaveSelector:contextInfo:
– printInfo
– setPrintInfo:
– preparePageLayout:
– runModalPageLayoutWithPrintInfo:delegate:didRunSelector:contextInfo:
– runModalPrintOperation:delegate:didRunSelector:contextInfo:
– shouldChangePrintInfo:
– printDocumentWithSettings:showPrintPanel:delegate:didPrintSelector:contextInfo:
– printOperationWithSettings:error:
– presentError:modalForWindow:delegate:didPresentSelector:contextInfo:
– presentError:
– willPresentError:
– setFileType:
– fileType
– fileTypeFromLastRunSavePanel
+ isNativeType:
+ readableTypes
+ writableTypes
– writableTypesForSaveOperation:
– fileNameExtensionForType:saveOperation:
– handleCloseScriptCommand:
– handlePrintScriptCommand:
– handleSaveScriptCommand:
– objectSpecifier
– lastComponentOfFileName
– setLastComponentOfFileName:
– validateMenuItem:
– canCloseDocument
– dataRepresentationOfType:
– fileAttributesToWriteToFile:ofType:saveOperation:
– fileName
– fileNameFromRunningSavePanelForSaveOperation:
– fileWrapperRepresentationOfType:
– initWithContentsOfFile:ofType:
– initWithContentsOfURL:ofType:
– loadDataRepresentation:ofType:
– loadFileWrapperRepresentation:ofType:
– printShowingPrintPanel:
– readFromFile:ofType:
– readFromURL:ofType:
– revertToSavedFromFile:ofType:
– revertToSavedFromURL:ofType:
– runModalPageLayoutWithPrintInfo:
– setFileName:
– saveToFile:saveOperation:delegate:didSaveSelector:contextInfo:
– shouldCloseWindowController:
– writeToFile:ofType:
– writeToFile:ofType:originalFile:saveOperation:
– writeToURL:ofType:
– writeWithBackupToFile:ofType:saveOperation:
Returns a Boolean value indicating whether document data of the specified type is a native type—one the receiver can both read and write.
+ (BOOL)isNativeType:(NSString *)aType
The string that identifies the document type to test.
YES if the document type is a native type; otherwise, NO.
NSDocument.h
Returns the types of data the receiver can read natively and any types filterable to that native type.
+ (NSArray *)readableTypes
An array of NSString objects representing the readable document types.
NSDocument.h
Returns the types of data the receiver can write natively and any types filterable to that native type.
+ (NSArray *)writableTypes
An array of NSString objects representing the writable document types.
NSDocument.hAdds the specified window controller to the array of window controllers associated with the receiver.
- (void)addWindowController:(NSWindowController *)aController
The window controller that is added.
An NSDocument object 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 self 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 the NSWindowController message close.
– setDocument: (NSWindowController)NSDocument.hReturns the location of the most recently autosaved document contents.
- (NSURL *)autosavedContentsFileURL
The location of the most recently autosaved document contents.
The default implementation of this method just returns whatever was stored by a previous invocation of the default implementation of setAutosavedContentsFileURL:.
NSDocument.hAutosaves the document’s contents at an appropriate location.
- (void)autosaveDocumentWithDelegate:(id)delegate didAutosaveSelector:(SEL)didAutosaveSelector contextInfo:(void *)contextInfo
The delegate to which the selector message is sent.
The selector of the message sent to the delegate.
Object passed with the callback to provide any additional context information.
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.
NSDocument.hReturns the document type that should be used for an autosave operation.
- (NSString *)autosavingFileType
The string that identifies the document type.
The default implementation just returns [self fileType]. You can override this method and return nil in your override to completely disable autosaving of individual documents (because NSDocumentController does not send autosaveDocumentWithDelegate:didAutosaveSelector:contextInfo: to a document that has no autosaving file type). 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.
NSDocument.hThis method is no longer supported. (Deprecated. Use canCloseDocumentWithDelegate:shouldCloseSelector:contextInfo: instead.)
- (BOOL)canCloseDocument
NSDocument.hIf the receiver is not dirty, this method immediately calls the shouldCloseSelector callback on the specified delegate with YES.
- (void)canCloseDocumentWithDelegate:(id)delegate shouldCloseSelector:(SEL)shouldCloseSelector contextInfo:(void *)contextInfo
The delegate to which the selector message is sent.
The selector of the message sent to the delegate.
Object passed with the callback to provide any additional context information.
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 YES. If the save is canceled or otherwise unsuccessful, this method calls the callback with NO. This method may be called by shouldCloseWindowController:delegate:shouldCloseSelector:contextInfo:. It is also called by the NSDocumentController method closeAllDocuments. 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 |
NSDocument.hCloses all windows owned by the receiver and removes the receiver from the list of documents maintained by the document controller, which consequently releases it.
- (void)close
This method closes the document immediately, without asking users if they want to save the document.
This method may not always be called. Additional information on application termination can be found in Graceful Application Termination.
– canCloseDocumentWithDelegate:shouldCloseSelector:contextInfo:– shouldCloseWindowController:delegate:shouldCloseSelector:contextInfo:NSDocument.hCreates and returns a data object that contains the contents of the document, formatted to a specified type.
- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError
The string that identifies the document type.
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.
A data object containing the document contents, or, if the data object could not be created, nil.
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 Mac OS X v10.3 and earlier, the default implementation of this method instead invokes dataRepresentationOfType:typeName on self if dataRepresentationOfType: is overridden.
NSDocument.hA primitive method overridden by subclasses to return a data object that represents the data of the receiver in a given type. (Deprecated. Use dataOfType:error: instead.)
- (NSData *)dataRepresentationOfType:(NSString *)aType
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])]; |
} |
NSDocument.h
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.
- (NSString *)displayName
The display name of the receiver.
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.
NSDocument.hReturns the file attributes that should be written to the named document file of the specified type. (Deprecated. Use fileAttributesToWriteToURL:ofType:forSaveOperation:originalContentsURL:error: instead.)
- (NSDictionary *)fileAttributesToWriteToFile:(NSString *)fullDocumentPath ofType:(NSString *)docType saveOperation:(NSSaveOperationType)saveOperationType
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.
NSDocument.hAs 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.
- (NSDictionary *)fileAttributesToWriteToURL:(NSURL *)absoluteURL ofType:(NSString *)typeName forSaveOperation:(NSSaveOperationType)saveOperation originalContentsURL:(NSURL *)absoluteOriginalContentsURL error:(NSError **)outError
The location to which the document is being written.
The string that identifies the document type.
The type of save operation.
The location of the previously saved copy of the document (if not nil).
On return, If the attributes could not be returned, a pointer to an error object that encapsulates the reason they could not be returned.
A dictionary containing the attributes to be written, or nil if unsuccessful.
The set of valid file attributes is a subset of those understood by the NSFileManager class. The default implementation of this method returns a dictionary with NSFileHFSCreatorCode and NSFileHFSTypeCode entries that have a value of 0 for NSSaveOperation, or a dictionary with an appropriate NSFileExtensionHidden entry for NSSaveAsOperation and NSSaveToOperation. 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 NSSaveAsOperation and NSSaveToOperation.
Invokers of this method should silently ignore invalid attributes. Of particular interest is the NSFileExtensionHidden attribute, which is documented in NSFileManager.
The dictionary returned by the default implementation of this method contains an NSFileExtensionHidden 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 writeSafelyToURL:ofType:forSaveOperation:error: should invoke this method and set the returned attributes on the written document file, possibly using the NSFileManager method changeFileAttributes:atPath:.
Implementers of overrides of this method should not assume that:
The file pointed to by absoluteURL at the moment the method is invoked, if there is one, is related to the document itself. It may be an unrelated file that is about to be overwritten.
The fileURL or fileType method will return anything useful at the moment.
NSDocument.hReturns the last known modification date of the document's on-disk representation.
- (NSDate *)fileModificationDate
The file modification date.
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 application.
NSDocument.hReturns the filename (as a fully qualified path) under which the receiver has been saved. (Deprecated. Use fileURL instead.)
- (NSString *)fileName
NSDocument.hReturns a filename extension that can be appended to a base filename, for a specified file type and kind of save operation.
- (NSString *)fileNameExtensionForType:(NSString *)typeName saveOperation:(NSSaveOperationType)saveOperation
The file type.
The kind of save operation.
The filename extension.
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 Mac 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. In Mac OS X v10.5, it's only invoked from two places in the Application Kit:
The autosaveDocumentWithDelegate:didAutosaveSelector:contextInfo: method uses this method when creating a new filename for the autosaved contents.
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).
NSDocument.hReturns YES if a Save panel was presented by this document and the user chose to hide the name extension of the file that was selected in that Save panel.
- (BOOL)fileNameExtensionWasHiddenInLastRunSavePanel
YES if a Save panel was presented and the user chose to hide the extension; otherwise, NO.
NSDocument.hReturns the filename entered into the Save panel. (Deprecated. Use saveDocumentWithDelegate:didSaveSelector:contextInfo: instead.)
- (NSString *)fileNameFromRunningSavePanelForSaveOperation:(NSSaveOperationType)saveOperation
NSDocument.hReturns the document type under which the receiver is saved.
- (NSStri