NSDocument Class Reference

Inherits from
Conforms to
Framework
/System/Library/Frameworks/AppKit.framework
Availability
Available in OS X v10.0 and later.
Companion guide
Declared in
NSDocument.h
NSDocumentScripting.h
NSWindowRestoration.h
Related sample code

Overview

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

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

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

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

Subclassing NSDocument

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

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

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

Document Saving Behavior

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

  • Creation date

  • Permissions/privileges

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

  • Value of the document’s Show Extension setting

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

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

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

  • The relation of any file being passed, including the original file, to the return value of fileName.

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

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

iCloud Support

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

Multicore Considerations

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

Tasks

Initializing

Loading Document Data

Creating and Managing Window Controllers

Managing Document Windows

Reading From and Writing to Files

Reading From and Writing to URLs

Serialization

Autosaving

ICloud Document Storage

Handling Window Restoration

Managing Document Status

Handling User Actions

Closing Documents

Reverting Documents

Duplicating Documents

Renaming Documents

Moving Documents

Locking Documents

Printing Documents

Handling Errors

Working with Undo Manager

Managing File Types

Validating User Interface Items

Scripting

Deprecated Methods

Class Methods

autosavesDrafts

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

+ (BOOL)autosavesDrafts
Return Value

YES if the receiving subclass of NSDocument supports autosaving of drafts; otherwise NO.

Discussion

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

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

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

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

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

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

Availability
  • Available in OS X v10.8 and later.
Declared In
NSDocument.h

autosavesInPlace

Returns whether the receiver supports autosaving in place.

+ (BOOL)autosavesInPlace
Return Value

YES if the receiver supports autosaving in place; NO otherwise.

Discussion

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

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

Availability
  • Available in OS X v10.7 and later.
Declared In
NSDocument.h

canConcurrentlyReadDocumentsOfType:

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

+ (BOOL)canConcurrentlyReadDocumentsOfType:(NSString *)typeName
Parameters
typeName

The string that identifies the document type.

Return Value

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

Discussion

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

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

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

Availability
  • Available in OS X v10.6 and later.
Declared In
NSDocument.h

isNativeType:

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
Parameters
aType

The string that identifies the document type to test.

Return Value

YES if the document type is a native type; otherwise, NO.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

preservesVersions

Returns whether the receiving subclass of NSDocument supports Versions.

+ (BOOL)preservesVersions
Return Value

YES if the receiving subclass of NSDocument supports Versions; otherwise NO.

Discussion

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

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

Availability
  • Available in OS X v10.7 and later.
Declared In
NSDocument.h

readableTypes

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

+ (NSArray *)readableTypes
Return Value

An array of NSString objects representing the readable document types.

Availability
  • Available in OS X v10.0 and later.
Related Sample Code
Declared In
NSDocument.h

restorableStateKeyPaths

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

+ (NSArray *)restorableStateKeyPaths
Return Value

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

Discussion

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

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

Availability
  • Available in OS X v10.7 and later.
Declared In
NSWindowRestoration.h

usesUbiquitousStorage

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

+ (BOOL)usesUbiquitousStorage
Discussion

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

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

Availability
  • Available in OS X v10.8 and later.
Declared In
NSDocument.h

writableTypes

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

+ (NSArray *)writableTypes
Return Value

An array of NSString objects representing the writable document types.

Availability
  • Available in OS X v10.0 and later.
Related Sample Code
Declared In
NSDocument.h

Instance Methods

addWindowController:

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

- (void)addWindowController:(NSWindowController *)aController
Parameters
aController

The window controller that is added.

Discussion

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

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

You would not typically override this method.

Availability
  • Available in OS X v10.0 and later.
See Also
Declared In
NSDocument.h

autosavedContentsFileURL

Returns the location of the most recently autosaved document contents.

- (NSURL *)autosavedContentsFileURL
Return Value

The location of the most recently autosaved document contents.

Discussion

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

Availability
  • Available in OS X v10.4 and later.
Related Sample Code
Declared In
NSDocument.h

autosaveDocumentWithDelegate:didAutosaveSelector:contextInfo:

Autosaves the document’s contents at an appropriate location.

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

The delegate to which the selector message is sent.

didAutosaveSelector

The selector of the message sent to the delegate.

contextInfo

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

Discussion

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

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

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

Availability
  • Available in OS X v10.4 and later.
Declared In
NSDocument.h

autosaveWithImplicitCancellability:completionHandler:

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

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

The value returned by the autosavingIsImplicitlyCancellable method while autosaving is happening.

completionHandler

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

The block takes one argument:

errorOrNil

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

Discussion

The default implementation of this method does the following:

  1. Sends the hasUnautosavedChanges message to itself.

  2. If that method returns NO, the method runs the completion handler with a nil error and returns immediately.

    If that method returns YES, calls autosavesInPlace on the class to determine where the autosaved document contents should go.

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

  3. Calls autosavingFileType to determine the file type for the autosaved file.

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

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

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

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

Availability
  • Available in OS X v10.7 and later.
Related Sample Code
Declared In
NSDocument.h

autosavingFileType

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

- (NSString *)autosavingFileType
Return Value

The string that identifies the document type.

Discussion

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 app defines a document type that is specifically designed for autosaving, for example, one that efficiently represents document content changes instead of complete document contents.

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

Availability
  • Available in OS X v10.4 and later.
Related Sample Code
Declared In
NSDocument.h

autosavingIsImplicitlyCancellable

Returns whether autosaving is happening now but could be safely cancelled.

- (BOOL)autosavingIsImplicitlyCancellable
Return Value

YES if autosaving is being done now but nothing bad would happen if it were cancelled; NO otherwise.

Discussion

For example, when periodic autosaving is being done only for crash protection, which doesn’t need to be done all of the time, this method returns YES. When autosaving is being done because the document is being closed, this method returns NO.

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

Availability
  • Available in OS X v10.7 and later.
Declared In
NSDocument.h

backupFileURL

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

- (NSURL *)backupFileURL
Return Value

On successful backup, the location of the backup file; or nil if the backup file can’t be created or isn’t needed.

Discussion

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

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

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

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

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

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

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

Availability
  • Available in OS X v10.8 and later.
Declared In
NSDocument.h

browseDocumentVersions:

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

- (void)browseDocumentVersions:(id)sender
Parameters
sender

The control sending the message.

Discussion

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

Availability
  • Available in OS X v10.8 and later.
Declared In
NSDocument.h

canAsynchronouslyWriteToURL:ofType:forSaveOperation:

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.

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

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

typeName

The string that identifies the document type.

saveOperation

The type of save operation.

Return Value

NO by default; subclasses can override to return YES, thereby enabling asynchronous writing.

Discussion

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

Availability
  • Available in OS X v10.7 and later.
Declared In
NSDocument.h

canCloseDocumentWithDelegate:shouldCloseSelector:contextInfo:

If 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
Parameters
delegate

The delegate to which the selector message is sent.

shouldCloseSelector

The selector of the message sent to the delegate.

contextInfo

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

Discussion

If the receiver is dirty, an alert is presented giving the user a chance to save, not save, or cancel. If the user chooses to save, this method saves the document. If the save completes successfully, this method calls the callback with 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 closeAllDocumentsWithDelegate:didCloseAllSelector:contextInfo:. You should call it before you call close if you are closing the document and want to give the user a chance to save any edits. Pass the contextInfo object with the callback.

The shouldCloseSelector callback method should have the following signature:

- (void)document:(NSDocument *)doc shouldClose:(BOOL)shouldClose  contextInfo:(void  *)contextInfo
Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

changeCountTokenForSaveOperation:

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

- (id)changeCountTokenForSaveOperation:(NSSaveOperationType)saveOperation
Parameters
saveOperation

The type of save operation.

Return Value

An object encapsulating the document changes.

Discussion

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

Availability
  • Available in OS X v10.7 and later.
Declared In
NSDocument.h

checkAutosavingSafetyAndReturnError:

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

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

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

Return Value

YES if autosaving the document is probably safe; otherwise, NO.

Discussion

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

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

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

Availability
  • Available in OS X v10.7 and later.
Declared In
NSDocument.h

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.

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

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

continueActivityUsingBlock:

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

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

The block to be invoked.

Discussion

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

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

Availability
  • Available in OS X v10.7 and later.
Declared In
NSDocument.h

continueAsynchronousWorkOnMainThreadUsingBlock:

Invokes the passed-in block on the main thread.

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

The block to be invoked.

Discussion

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

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

This method can be invoked on any thread.

Availability
  • Available in OS X v10.7 and later.
Declared In
NSDocument.h

dataOfType:error:

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

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

The string that identifies the document type.

outError

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

Return Value

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

Discussion

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

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

Availability
  • Available in OS X v10.4 and later.
Declared In
NSDocument.h

defaultDraftName

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

- (NSString *)defaultDraftName
Discussion

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

When a document has not yet been assigned a name, and has not yet been autosaved with the NSAutosaveAsOperation save operation type, the document invokes this method from within the displayName method.

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

Availability
  • Available in OS X v10.8 and later.
Declared In
NSDocument.h

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.

- (NSString *)displayName
Return Value

The display name of the receiver.

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.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

duplicateAndReturnError:

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

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

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

Return Value

The new document if duplication is successful; otherwise nil.

Discussion

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

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

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

Availability
  • Available in OS X v10.7 and later.
Declared In
NSDocument.h

duplicateDocument:

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

- (void)duplicateDocument:(id)sender
Parameters
sender

The control sending the action message.

Discussion

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

Availability
  • Available in OS X v10.7 and later.
Declared In
NSDocument.h

duplicateDocumentWithDelegate:didDuplicateSelector:contextInfo:

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

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

The delegate to which the selector message is sent.

didDuplicateSelector

The selector of the message sent to the delegate.

contextInfo

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

Discussion

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

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

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

Availability
  • Available in OS X v10.7 and later.
Declared In
NSDocument.h

encodeRestorableStateWithCoder:

Saves the interface-related state of the document.

- (void)encodeRestorableStateWithCoder:(NSCoder *)coder
Parameters
coder

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

Discussion

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

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

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

Availability
  • Available in OS X v10.7 and later.
Declared In
NSWindowRestoration.h

fileAttributesToWriteToURL:ofType:forSaveOperation:originalContentsURL:error:

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.

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

The location to which the document is being written.

typeName

The string that identifies the document type.

saveOperation

The type of save operation.

absoluteOriginalContentsURL

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

outError

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

Return Value

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

Discussion

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

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

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

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

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

Availability
  • Available in OS X v10.4 and later.
Declared In
NSDocument.h

fileModificationDate

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

- (NSDate *)fileModificationDate
Return Value

The file modification date.

Discussion

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

Availability
  • Available in OS X v10.4 and later.
Declared In
NSDocument.h

fileNameExtensionForType:saveOperation:

Returns 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
Parameters
typeName

The file type.

saveOperation

The kind of save operation.

Return Value

The filename extension.

Discussion

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

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

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

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

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

Availability
  • Available in OS X v10.5 and later.
Declared In
NSDocument.h

fileNameExtensionWasHiddenInLastRunSavePanel

Returns 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
Return Value

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

Availability
  • Available in OS X v10.1 and later.
Declared In
NSDocument.h

fileType

Returns the document type under which the receiver is saved.

- (NSString *)fileType
Return Value

The string that identifies the document type.

Discussion

When a document is saved, the type is determined by the entries in the app’s information property list (specified in Info.plist).

Availability
  • Available in OS X v10.0 and later.
Related Sample Code
Declared In
NSDocument.h

fileTypeFromLastRunSavePanel

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

- (NSString *)fileTypeFromLastRunSavePanel
Return Value

The string that identifies the document type.

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.

Availability
  • Available in OS X v10.0 and later.
Related Sample Code
Declared In
NSDocument.h

fileURL

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

- (NSURL *)fileURL
Return Value

The document’s location.

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 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
  • Available in OS X v10.4 and later.
Declared In
NSDocument.h

fileWrapperOfType:error:

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

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

The string that identifies the document type.

outError

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

Return Value

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

Discussion

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

Availability
  • Available in OS X v10.4 and later.
Declared In
NSDocument.h

handleCloseScriptCommand:

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

- (id)handleCloseScriptCommand:(NSCloseCommand *)command
Parameters
command

A Close AppleScript command object.

Discussion

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

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocumentScripting.h

handlePrintScriptCommand:

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

- (id)handlePrintScriptCommand:(NSScriptCommand *)command
Parameters
command

An AppleScript command object.

Discussion

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

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocumentScripting.h

handleSaveScriptCommand:

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

- (id)handleSaveScriptCommand:(NSScriptCommand *)command
Parameters
command

An AppleScript command object.

Discussion

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

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocumentScripting.h

hasUnautosavedChanges

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

- (BOOL)hasUnautosavedChanges
Return Value

YES if the document has changes that have not been autosaved; otherwise, NO.

Availability
  • Available in OS X v10.4 and later.
Declared In
NSDocument.h

hasUndoManager

Returns a Boolean value indicating whether the receiver owns or should own an NSUndoManager object.

- (BOOL)hasUndoManager
Return Value

YES if the receiver has its own undo manager; otherwise, NO.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

init

Initializes and returns an empty NSDocument object.

- (id)init
Return Value

An initialized NSDocument object.

Discussion

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

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

Availability
  • Available in OS X v10.0 and later.
Related Sample Code
Declared In
NSDocument.h

initForURL:withContentsOfURL:ofType:error:

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

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

The URL where the document is located.

absoluteDocumentContentsURL

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

typeName

The string that identifies the document type.

outError

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

Return Value

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

Discussion

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

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

NSChangeReadOtherContents

Availability
  • Available in OS X v10.4 and later.
Declared In
NSDocument.h

initWithContentsOfURL:ofType:error:

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

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

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

typeName

The string that identifies the document type.

outError

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

Return Value

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

Discussion

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

This method is invoked by the NSDocumentController method makeDocumentWithContentsOfURL:ofType:error:. The default implementation of this method invokes init, readFromURL:ofType:error:, setFileURL:, setFileType:, and setFileModificationDate:.

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

Availability
  • Available in OS X v10.4 and later.
Declared In
NSDocument.h

initWithType:error:

Initializes a document of a specified type.

- (id)initWithType:(NSString *)typeName error:(NSError **)outError
Parameters
typeName

The string that identifies the document type.

outError

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

Return Value

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

Discussion

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

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

Availability
  • Available in OS X v10.4 and later.
Declared In
NSDocument.h

invalidateRestorableState

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

- (void)invalidateRestorableState
Discussion

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

Availability
  • Available in OS X v10.7 and later.
Declared In
NSWindowRestoration.h

isDocumentEdited

Returns YES if the receiver has changes that have not been saved, NO otherwise.

- (BOOL)isDocumentEdited
Return Value

YES if the receiver has been edited; otherwise, NO.

Discussion

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

Availability
  • Available in OS X v10.0 and later.
Related Sample Code
Declared In
NSDocument.h

isDraft

Whether the document is a draft that the user has not expressed an interest in keeping around.

- (BOOL)isDraft
Discussion

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

Availability
  • Available in OS X v10.8 and later.
Declared In
NSDocument.h

isEntireFileLoaded

Returns whether the document’s file is completely loaded into memory.

- (BOOL)isEntireFileLoaded
Return Value

YES if the document’s entire file is loaded into memory; otherwise NO.

Discussion

The default implementation of this method returns YES. You can override this method to return NO if additional data needs to be read from the file. NSDocument may use this value to do things like prevent volume ejection or warn the user when a partially loaded file disappears from the file system.

Availability
  • Available in OS X v10.7 and later.
Declared In
NSDocument.h

isInViewingMode

Returns whether the document is in read-only mode.

- (BOOL)isInViewingMode
Return Value

YES if the document is in read-only mode; otherwise, NO.

Discussion

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

Availability
  • Available in OS X v10.7 and later.
Declared In
NSDocument.h

isLocked

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

- (BOOL)isLocked
Return Value

YES if the file cannot be written to; otherwise, NO.

Discussion

The reasons for this returning YES may include the lack of write permissions, the “user immutable” flag being raised, the presence of a read-only parent directory or volume, or a return value of NO from the checkAutosavingSafetyAndReturnError: method. This method should not be overridden.

Availability
  • Available in OS X v10.8 and later.
Declared In
NSDocument.h

keepBackupFile

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

- (BOOL)keepBackupFile
Return Value

NO by default; subclasses can override to return YES, thereby causing backup files to be kept.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

lastComponentOfFileName

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

- (NSString *)lastComponentOfFileName
Return Value

The scripting name of the document.

Discussion

Note that this name may be different than the name returned by fileName or used in methods such as writeToFile:ofType:.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocumentScripting.h

lockDocument:

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

- (void)lockDocument:(id)sender
Parameters
sender

The control sending the message.

Discussion

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

Availability
  • Available in OS X v10.8 and later.
Declared In
NSDocument.h

lockDocumentWithCompletionHandler:

Prevents the user from making further changes to the document.

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

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

Discussion

By default, this method first ensures that any editor who has registered using Cocoa Binding’s NSEditorRegistration informal protocol has committed all changes and then autosaves the document, if necessary, before attempting to lock it using the lockWithCompletionHandler: method. Upon successful locking, the isLocked method will begin returning [YES]. Note: documents that return nil from [self fileURL] cannot be locked.

Availability
  • Available in OS X v10.8 and later.
Declared In
NSDocument.h

lockWithCompletionHandler:

Prevents further modifications from being made to the file.

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

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

Discussion

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

Availability
  • Available in OS X v10.8 and later.
Declared In
NSDocument.h

makeWindowControllers

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

- (void)makeWindowControllers
Discussion

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

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

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

moveDocument:

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

- (void)moveDocument:(id)sender
Parameters
sender

The control sending the message.

Discussion

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

Availability
  • Available in OS X v10.8 and later.
Declared In
NSDocument.h

moveDocumentToUbiquityContainer:

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

- (void)moveDocumentToUbiquityContainer:(id)sender
Parameters
sender

The control sending the message.

Discussion

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

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

Availability
  • Available in OS X v10.8 and later.
Declared In
NSDocument.h

moveDocumentWithCompletionHandler:

Moves the document to a user-selected location.

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

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

Discussion

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

Availability
  • Available in OS X v10.8 and later.
Declared In
NSDocument.h

moveToURL:completionHandler:

Moves the document’s file to the given URL.

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

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

completionHandler

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

Discussion

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

Availability
  • Available in OS X v10.8 and later.
Declared In
NSDocument.h

objectSpecifier

Returns an object specifier for the document.

- (NSScriptObjectSpecifier *)objectSpecifier
Return Value

The document object specifier.

Discussion

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

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocumentScripting.h

PDFPrintOperation

Returns a print operation that creates a PDF representation of the document’s current contents.

- (NSPrintOperation *)PDFPrintOperation
Discussion

The returned print operation can be run to print the document’s current contents to a PDF file.

The default implementation of this method invokes printOperationWithSettings:error:, passing a print settings object that contains only the disposition (NSPrintSaveJob) and a NULL error object reference. If your document subclass supports creating PDF representations, you can override this method, if needed.

Availability
  • Available in OS X v10.9 and later.
Declared In
NSDocument.h

performActivityWithSynchronousWaiting:usingBlock:

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

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

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

inBlock

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

Discussion

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

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

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

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

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

autosaveDocumentWithDelegate:didAutosaveSelector:contextInfo:

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

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

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

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

Availability
  • Available in OS X v10.7 and later.
Related Sample Code
Declared In
NSDocument.h

performAsynchronousFileAccessUsingBlock:

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

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

A block that performs file access.

Discussion

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

Availability
  • Available in OS X v10.7 and later.
Declared In
NSDocument.h

performSynchronousFileAccessUsingBlock:

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

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

A block that performs file access.

Discussion

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

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

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

Availability
  • Available in OS X v10.7 and later.
Related Sample Code
Declared In
NSDocument.h

preparePageLayout:

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

- (BOOL)preparePageLayout:(NSPageLayout *)pageLayout
Parameters
pageLayout

The page layout panel to prepare.

Return Value

YES if successfully prepared; otherwise, NO.

Discussion

The default implementation is empty and returns YES.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

prepareSavePanel:

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

- (BOOL)prepareSavePanel:(NSSavePanel *)savePanel
Parameters
savePanel

The Save panel.

Return Value

YES if successfully prepared; otherwise, NO.

Discussion

The default implementation is empty and returns YES.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

presentError:

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

- (BOOL)presentError:(NSError *)error
Parameters
error

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

Return Value

YES if error recovery was done; otherwise, NO.

Discussion

This method does not return until the user dismisses the alert and, if the error has recovery options and a recovery delegate, the error’s recovery delegate is sent an attemptRecoveryFromError:optionIndex: message.

The NSDocument default implementation of this method is equivalent to that of NSResponder and treats the shared NSDocumentController as the next responder and forwards these messages to it.

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

Availability
  • Available in OS X v10.4 and later.
Related Sample Code
Declared In
NSDocument.h

presentError:modalForWindow:delegate:didPresentSelector:contextInfo:

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

- (void)presentError:(NSError *)error modalForWindow:(NSWindow *)window delegate:(id)delegate didPresentSelector:(SEL)didPresentSelector contextInfo:(void *)contextInfo
Parameters
error

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

window

The window to which the modal alert belongs.

delegate

The delegate to which the selector message is sent.

didPresentSelector

The selector of the message sent to the delegate.

contextInfo

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

Discussion

When the user dismisses the alert and any recovery possible for the error and chosen by the user has been attempted, sends the message didPresentSelector to the specified delegate.

The NSDocument default implementation of this method is equivalent to that of NSResponder and treats the shared NSDocumentController object as the next responder and forwards these messages to it. The default implementations of several NSDocument methods invoke this method.

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

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

- (void)didPresentErrorWithRecovery:(BOOL)didRecover contextInfo:(void  *)contextInfo
Availability
  • Available in OS X v10.4 and later.
Related Sample Code
Declared In
NSDocument.h

printDocument:

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

- (void)printDocument:(id)sender
Parameters
sender

The control sending the message.

Discussion

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

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

printDocumentWithSettings:showPrintPanel:delegate:didPrintSelector:contextInfo:

Prints the document.

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

The print settings dictionary to use.

showPrintPanel

A Boolean value indicating whether the print panel is shown.

delegate

The delegate to which the selector message is sent.

didPrintSelector

The selector of the message sent to the delegate.

contextInfo

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

Discussion

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

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

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

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

Availability
  • Available in OS X v10.4 and later.
Declared In
NSDocument.h

printInfo

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

- (NSPrintInfo *)printInfo
Return Value

The receiver’s NSPrintInfo object.

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.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

printOperationWithSettings:error:

Creates a print operation and returns it if successful.

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

The print settings dictionary to use.

outError

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

Return Value

The print operation, or nil if unsuccessful.

Discussion

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

Availability
  • Available in OS X v10.4 and later.
Declared In
NSDocument.h

readFromData:ofType:error:

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

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

The data object from which the document contents are read.

typeName

The string that identifies the document type.

outError

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

Return Value

YES if the document contents could be read; otherwise, NO.

Discussion

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

Availability
  • Available in OS X v10.4 and later.
Declared In
NSDocument.h

readFromFileWrapper:ofType:error:

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

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

The file wrapper from which the document contents are read.

typeName

The string that identifies the document type.

outError

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

Return Value

YES if the document contents could be read; otherwise, NO.

Discussion

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

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

Availability
  • Available in OS X v10.4 and later.
Declared In
NSDocument.h

readFromURL:ofType:error:

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

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

The location from which the document contents are read.

typeName

The string that identifies the document type.

outError

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

Return Value

YES if the document contents could be read; otherwise, NO.

Discussion

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

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

Availability
  • Available in OS X v10.4 and later.
Declared In
NSDocument.h

removeWindowController:

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

- (void)removeWindowController:(NSWindowController *)windowController
Parameters
windowController

The window controller that is removed.

Discussion

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

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

Availability
  • Available in OS X v10.0 and later.
See Also
Related Sample Code
Declared In
NSDocument.h

renameDocument:

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

- (void)renameDocument:(id)sender
Parameters
sender

The control sending the message.

Discussion

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

Availability
  • Available in OS X v10.8 and later.
Declared In
NSDocument.h

restoreDocumentWindowWithIdentifier:state:completionHandler:

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

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

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

state

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

completionHandler

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

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

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

Discussion

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

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

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

Availability
  • Available in OS X v10.7 and later.
Declared In
NSWindowRestoration.h

restoreStateWithCoder:

Restores the interface-related state of the document.

- (void)restoreStateWithCoder:(NSCoder *)coder
Parameters
coder

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

Discussion

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

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

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

Availability
  • Available in OS X v10.7 and later.
Declared In
NSWindowRestoration.h

revertDocumentToSaved:

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

- (void)revertDocumentToSaved:(id)sender
Parameters
sender

The control sending the message.

Discussion

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

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

revertToContentsOfURL:ofType:error:

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.

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

The location from which the document contents are read.

typeName

The string that identifies the document type.

outError

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

Return Value

YES if the document could be reverted; otherwise, NO.

Availability
  • Available in OS X v10.4 and later.
Declared In
NSDocument.h

runModalPageLayoutWithPrintInfo:delegate:didRunSelector:contextInfo:

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

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

The NSPrintInfo object for the page layout panel to use.

delegate

The delegate to which the selector message is sent.

didRunSelector

The selector of the message sent to the delegate.

contextInfo

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

Discussion

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

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

- (void)documentDidRunModalPageLayout:(NSDocument *)document accepted:(BOOL)accepted  contextInfo:(void *)contextInfo
Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

runModalPrintOperation:delegate:didRunSelector:contextInfo:

Runs the specified print operation modally.

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

The print operation to run.

delegate

The delegate to which the selector message is sent.

didRunSelector

The selector of the message sent to the delegate.

contextInfo

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

Discussion

Overrides of printShowingPrintPanel: can invoke this method.

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

- (void)documentDidRunModalPrintOperation:(NSDocument *)document  success:(BOOL)success  contextInfo:(void *)contextInfo
Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

runModalSavePanelForSaveOperation:delegate:didSaveSelector:contextInfo:

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

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

The type of save operation.

delegate

The delegate to which the selector message is sent.

didSaveSelector

The selector of the message sent to the delegate.

contextInfo

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

Discussion

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

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

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

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

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

runPageLayout:

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

- (void)runPageLayout:(id)sender
Parameters
sender

The control sending the message.

Discussion

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

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

saveDocument:

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

- (void)saveDocument:(id)sender
Parameters
sender

The control sending the message.

Discussion

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

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

saveDocumentAs:

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

- (void)saveDocumentAs:(id)sender
Parameters
sender

The control sending the message.

Discussion

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

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

saveDocumentTo:

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

- (void)saveDocumentTo:(id)sender
Parameters
sender

The control sending the message.

Discussion

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

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

saveDocumentToPDF:

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

- (void)saveDocumentToPDF:(id)sender
Parameters
sender

The control sending the message.

Discussion

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

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

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

Availability
  • Available in OS X v10.9 and later.
Declared In
NSDocument.h

saveDocumentWithDelegate:didSaveSelector:contextInfo:

Saves the document.

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

The delegate to which the selector message is sent.

didSaveSelector

The selector of the message sent to the delegate.

contextInfo

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

Discussion

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

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

The didSaveSelector callback method should have the following signature:

- (void)document:(NSDocument *)doc didSave:(BOOL)didSave contextInfo:(void  *)contextInfo
Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

saveToURL:ofType:forSaveOperation:completionHandler:

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.

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

The location to which the document contents are written.

typeName

The document type.

saveOperation

The type of save operation.

completionHandler

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

The block takes one argument:

errorOrNil

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

Discussion

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

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

Availability
  • Available in OS X v10.7 and later.
Related Sample Code
Declared In
NSDocument.h

saveToURL:ofType:forSaveOperation:delegate:didSaveSelector:contextInfo:

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.

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

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

typeName

The string that identifies the document type.

saveOperation

The type of save operation.

delegate

The delegate to which the selector message is sent.

didSaveSelector

The selector of the message sent to the delegate.

contextInfo

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

Discussion

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

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

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

Availability
  • Available in OS X v10.4 and later.
Declared In
NSDocument.h

scheduleAutosaving

Schedules periodic autosaving for the purpose of crash protection.

- (void)scheduleAutosaving
Discussion

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

Availability
  • Available in OS X v10.7 and later.
Declared In
NSDocument.h

setAutosavedContentsFileURL:

Sets the location of the most recently autosaved document contents.

- (void)setAutosavedContentsFileURL:(NSURL *)absoluteURL
Parameters
absoluteURL

The location of the most recently autosaved document contents.

Discussion

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

Availability
  • Available in OS X v10.4 and later.
Declared In
NSDocument.h

setDisplayName:

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

- (void)setDisplayName:(NSString *)displayNameOrNil
Parameters
displayNameOrNil

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

Availability
  • Available in OS X v10.7 and later.
Declared In
NSDocument.h

setDraft:

Sets whether or not the document is considered to be a draft.

- (void)setDraft:(BOOL)flag
Availability
  • Available in OS X v10.8 and later.
See Also
Declared In
NSDocument.h

setFileModificationDate:

Sets the last known modification date of the document’s on-disk representation to the given modification date.

- (void)setFileModificationDate:(NSDate *)modificationDate
Parameters
modificationDate

The date to which the file modification date is set.

Discussion

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

Availability
  • Available in OS X v10.4 and later.
Declared In
NSDocument.h

setFileType:

Sets the document type under which the file is saved.

- (void)setFileType:(NSString *)docType
Parameters
docType

The string that identifies the document type.

Discussion

The document type affects how the data is filtered when it is written to or read from a file. This method isn’t for changing the document’s format; it’s just for initially recording the document’s format during opening or saving.

Availability
  • Available in OS X v10.0 and later.
See Also
Related Sample Code
Declared In
NSDocument.h

setFileURL:

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

- (void)setFileURL:(NSURL *)absoluteURL
Parameters
absoluteURL

The document’s location.

Discussion

This method doesn’t actually rename the document; it is 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 OS X v10.3 and earlier, if setFileName: is overridden and the URL is nil or uses the file: scheme, the default implementation of this method instead invokes [self setFileName:[absoluteURL path]].

Availability
  • Available in OS X v10.4 and later.
See Also
Related Sample Code
Declared In
NSDocument.h

setHasUndoManager:

Sets whether the receiver has its own NSUndoManager object.

- (void)setHasUndoManager:(BOOL)flag
Parameters
flag

A Boolean value setting whether the receiver should own an NSUndoManager object.

Discussion

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

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

setLastComponentOfFileName:

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

- (void)setLastComponentOfFileName:(NSString *)str
Parameters
str

The scripting name of the document.

Discussion

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

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocumentScripting.h

setPrintInfo:

Sets the receiver’s NSPrintInfo object.

- (void)setPrintInfo:(NSPrintInfo *)printInfo
Parameters
printInfo

The NSPrintInfo object for the receiver to use.

Discussion

This NSPrintInfo object is used in laying out the document for printing.

Availability
  • Available in OS X v10.0 and later.
Related Sample Code
Declared In
NSDocument.h

setUndoManager:

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

- (void)setUndoManager:(NSUndoManager *)undoManager
Parameters
undoManager

The undo manager to be owned by the receiver; may be nil.

Discussion

If undoManager is nil, it turns off the hasUndoManager flag. If undoManager is non-nil, it adds the receiver as an observer of NSUndoManagerDidUndoChangeNotification, NSUndoManagerDidRedoChangeNotification, and NSUndoManagerWillCloseUndoGroupNotification.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

setWindow:

Sets the window Interface Builder outlet of this class.

- (void)setWindow:(NSWindow *)aWindow
Parameters
aWindow

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

Discussion

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

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

shouldChangePrintInfo:

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

- (BOOL)shouldChangePrintInfo:(NSPrintInfo *)newPrintInfo
Parameters
newPrintInfo

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

Return Value

YES by default; subclasses can override this method to return NO.

Discussion

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

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

shouldCloseWindowController:delegate:shouldCloseSelector:contextInfo:

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

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

The window controller that is closed.

delegate

The delegate to which the selector message is sent.

shouldCloseSelector

The selector of the message sent to the delegate.

contextInfo

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

Discussion

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

The shouldCloseSelector callback method should have the following signature:

- (void)document:(NSDocument *)document shouldClose:(BOOL)shouldClose  contextInfo:(void  *)contextInfo
Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

shouldRunSavePanelWithAccessoryView

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

- (BOOL)shouldRunSavePanelWithAccessoryView
Return Value

YES by default; subclasses can override to return NO, thereby excluding the accessory view from the Save panel.

Discussion

Here is an example implementation:

- (BOOL)shouldRunSavePanelWithAccessoryView {
    return [self fileName] == nil;
}
Availability
  • Available in OS X v10.0 and later.
Related Sample Code
Declared In
NSDocument.h

showWindows

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

- (void)showWindows
Availability
  • Available in OS X v10.0 and later.
Related Sample Code
Declared In
NSDocument.h

unblockUserInteraction

Unblocks the main thread during asynchronous saving.

- (void)unblockUserInteraction
Discussion

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

Availability
  • Available in OS X v10.7 and later.
Declared In
NSDocument.h

undoManager

Returns the receiver’s undo manager.

- (NSUndoManager *)undoManager
Return Value

The NSUndoManager object used by the receiver or nil if the receiver should not own one.

Discussion

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

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

unlockDocument:

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

- (void)unlockDocument:(id)sender
Parameters
sender

The control sending the message.

Discussion

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

Availability
  • Available in OS X v10.8 and later.
Declared In
NSDocument.h

unlockDocumentWithCompletionHandler:

Allows the user to make modifications to the document.

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

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

Discussion

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

Availability
  • Available in OS X v10.8 and later.
Declared In
NSDocument.h

unlockWithCompletionHandler:

Allows the user to make modifications to the file.

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

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

Discussion

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

Availability
  • Available in OS X v10.8 and later.
Declared In
NSDocument.h

updateChangeCount:

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

- (void)updateChangeCount:(NSDocumentChangeType)changeType
Parameters
changeType

The type of change made to the document.

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. The changeType is described in “Constants.” If you are implementing undo and redo in an app, you should increment the change count every time you create an undo group and decrement the change count when an undo or redo operation is performed.

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

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

updateChangeCountWithToken:forSaveOperation:

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

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

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

saveOperation

The type of save operation.

Discussion

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

Availability
  • Available in OS X v10.7 and later.
Declared In
NSDocument.h

validateUserInterfaceItem:

Validates the specified user interface item that the receiver manages.

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

The user interface item to validate.

Return Value

YES if the item is valid; otherwise, NO.

Discussion

These items currently include only Revert (which is enabled only if the document has a fileName) and Save. You can override this method to add more selectors validated by your document subclass.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

willNotPresentError:

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.

- (void)willNotPresentError:(NSError *)error
Parameters
error

An NSError object returned by another NSDocument method.

Discussion

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

Availability
  • Available in OS X v10.7 and later.
Declared In
NSDocument.h

willPresentError:

Called when the receiver is about to present an error.

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

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

Return Value

The error that should actually be presented.

Discussion

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

You can override this method to customize the presentation of errors by examining the passed-in error and, for example, returning more specific information. When you override this method always check the NSError object’s domain and code to discriminate between errors whose presentation you want to customize and those you don’t. For errors you don’t want to customize, call the superclass implementation, passing the original error.

Availability
  • Available in OS X v10.4 and later.
Declared In
NSDocument.h

windowControllerDidLoadNib:

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

- (void)windowControllerDidLoadNib:(NSWindowController *)windowController
Parameters
windowController

The window controller that loads the nib file.

Discussion

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

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

The default implementation of this method does nothing.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

windowControllers

Returns the receiver’s current window controllers.

- (NSArray *)windowControllers
Return Value

An array containing NSWindowController objects belonging to the current document. If there are no window controllers, returns an empty NSArray object.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

windowControllerWillLoadNib:

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

- (void)windowControllerWillLoadNib:(NSWindowController *)windowController
Parameters
windowController

The window controller that loads the nib file.

Discussion

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

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

The default implementation of this method does nothing.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

windowForSheet

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

- (NSWindow *)windowForSheet
Return Value

The window to use as the parent window of the sheet.

Discussion

May return nil, in which case the sender should present an app-modal panel. The NSDocument implementation of this method returns the window of the first window controller, or [NSApp mainWindow] if there are no window controllers or if the first window controller has no window.

Availability
  • Available in OS X v10.3 and later.
Declared In
NSDocument.h

windowNibName

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

- (NSString *)windowNibName
Return Value

The name of the document nib file.

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

Availability
  • Available in OS X v10.0 and later.
Related Sample Code
Declared In
NSDocument.h

writableTypesForSaveOperation:

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

- (NSArray *)writableTypesForSaveOperation:(NSSaveOperationType)saveOperation
Parameters
saveOperation

The kind of save operation.

Return Value

An array of NSString objects representing the writable document types.

Discussion

The save operation type is represented by saveOperation. For every kind of save operation except NSSaveToOperation, the returned array must only include types for which the the app can play the Editor role. For NSSaveToOperation the returned array may include types for which the app can only play the Viewer role, and other types that the app can merely export. The default implementation of this method returns [[self class] writableTypes] with, except during NSSaveToOperation, types for which isNativeType: returns NO 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
  • Available in OS X v10.4 and later.
Declared In
NSDocument.h

writeSafelyToURL:ofType:forSaveOperation:error:

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

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

The location to which the document contents are written.

typeName

The string that identifies the document type.

saveOperation

The type of save operation.

outError

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

Return Value

YES if the document contents could be written; otherwise, NO.

Discussion

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

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

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

Availability
  • Available in OS X v10.4 and later.
Declared In
NSDocument.h

writeToURL:ofType:error:

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

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

The location to which the document contents are written.

typeName

The string that identifies the document type.

outError

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

Return Value

YES if the document contents could be written; otherwise, NO.

Discussion

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

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

Availability
  • Available in OS X v10.4 and later.
Declared In
NSDocument.h

writeToURL:ofType:forSaveOperation:originalContentsURL:error:

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

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

The location to which the document contents are written.

typeName

The string that identifies the document type.

saveOperation

The type of save operation.

absoluteOriginalContentsURL

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

outError

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

Return Value

YES if the document contents could be written; otherwise, NO.

Discussion

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

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

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

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

Availability
  • Available in OS X v10.4 and later.
Declared In
NSDocument.h

Constants

Save Operation Types

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

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

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

Available in OS X v10.0 and later.

Declared in NSDocument.h.

NSSaveAsOperation

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

Available in OS X v10.0 and later.

Declared in NSDocument.h.

NSSaveToOperation

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

Available in OS X v10.0 and later.

Declared in NSDocument.h.

NSAutosaveElsewhereOperation

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

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

Available in OS X v10.7 and later.

Declared in NSDocument.h.

NSAutosaveInPlaceOperation

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

Available in OS X v10.7 and later.

Declared in NSDocument.h.

NSAutosaveAsOperation

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

Available in OS X v10.8 and later.

Declared in NSDocument.h.

NSAutosaveOperation

Old name for the NSAutosaveElsewhereOperation operation type. (Deprecated. Deprecated in OS X v10.7. Use NSAutosaveElsewhereOperation instead.)

Available in OS X v10.4 and later.

Declared in NSDocument.h.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h

NSDocumentChangeType

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

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

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

Available in OS X v10.0 and later.

Declared in NSDocument.h.

NSChangeUndone

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

Available in OS X v10.0 and later.

Declared in NSDocument.h.

NSChangeCleared

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

Available in OS X v10.0 and later.

Declared in NSDocument.h.

NSChangeReadOtherContents

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

Available in OS X v10.4 and later.

Declared in NSDocument.h.

NSChangeAutosaved

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

Available in OS X v10.4 and later.

Declared in NSDocument.h.

NSChangeRedone

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

Available in OS X v10.5 and later.

Declared in NSDocument.h.

NSChangeDiscardable

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

Available in OS X v10.7 and later.

Declared in NSDocument.h.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSDocument.h