UIDocument Class Reference
| Inherits from | |
| Conforms to | |
| Framework | /System/Library/Frameworks/UIKit.framework |
| Availability | Available in iOS 5.0 and later. |
| Companion guide | |
| Declared in | UIDocument.h |
Overview
The UIDocument class is an abstract base class for managing the data of documents.
Applications that make use of UIDocument and its underlying architecture get many benefits for their documents:
Asynchronous reading and writing of data on a background queue. Your application's responsiveness to users is thus unaffected while reading and writing operations are taking place.
Coordinated reading and writing of document files that is automatically integrated with cloud services.
Support for discovering conflicts between different versions of a document (if that occurs).
Safe-saving of document data by writing data first to a temporary file and then replacing the current document file with it.
Automatic saving of document data at opportune moments; this mechanism includes support for dealing with suspend behaviors.
In the Model-View-Controller design pattern, a UIDocument object is a model object or model-controller object—it manages the data of a document or the aggregate model objects that together constitute the document's data. You typically pair it with a view controller that manages the view presenting the document’s contents. UIDocument provides no support for managing document views.
Document-based applications include those that can generate multiple documents, each with its own file-system location. A document-based application must create a subclass of UIDocument for its documents. See “Subclassing Notes,” below, for details.
The primary attribute of a document in the UIDocument architecture is its file URL. When you initialize an instance of your document subclass by calling initWithFileURL:, you must pass a file URL locating the document file in the application sandbox. UIDocument determines the file type (the Uniform Type Identifier associated with the file extension) and the document name (the filename component) from the file URL. You can override the accessor methods of the fileType and localizedName properties to supply different values.
The following outlines the life cycle of a typical document (see “Subclassing Notes” for implementation details):
You create a new document or open an existing document.
To create a new document, allocate and initialize an instance of your subclass and then call
saveToURL:forSaveOperation:completionHandler:on the instance.To open an existing document (selected by the user), allocate and initialize an instance of your subclass and then call
openWithCompletionHandler:on the instance.
The user edits the document.
As the user edits, track changes to the document.
UIDocumentperiodically notes when there are unsaved changes and writes the document data to its file.The user requests that the document to be integrated with cloud services (optional).
You must enable the document for cloud storage. You must also resolve any conflicts between different versions of the same document.
The user closes the document.
Call
closeWithCompletionHandler:on the document instance.UIDocumentsaves the document if there are any unsaved changes.
A typical document-based application calls openWithCompletionHandler:, closeWithCompletionHandler:, and saveToURL:forSaveOperation:completionHandler: on the main thread. When the read or save operation kicked off by these methods concludes, the completion-handler block is executed on the same dispatch queue on which the method was invoked, allowing you to complete any tasks contingent on the read or save operation. If the operation is not successful, NO is passed into the completion-hander block.
Implementation of NSFilePresenter Protocol
The UIDocument class adopts the NSFilePresenter protocol. When another client attempts to read the document of a UIDocument-based application, that reading is suspended until the UIDocument object is given an opportunity to save any changes made to the document.
Although some implementations do nothing, UIDocument implements all NSFilePresenter methods, . Specifically, UIDocument:
Implements
relinquishPresentedItemToReader:to forward the incoming block toperformAsynchronousFileAccessUsingBlock:.Implements
relinquishPresentedItemToWriter:to check if the file-modification date has changed; if the file is newer than before, it callsrevertToContentsOfURL:completionHandler:with the value of thefileURLas the URL parameter.Implements
presentedItemDidMoveToURL:to update the document’s file URL (fileURL).
In your UIDocument subclass, if you override a NSFilePresenter method you can always invoke the superclass implementation (super).
Subclassing Notes
Each document-based application must create a subclass of UIDocument whose instances represent its documents. The subclassing requirements for most applications are simple:
For writing operations, implement the
contentsForType:error:method to provide a snapshot of document data. The data must be in the form of anNSDataobject (for flat files) or anNSFileWrapperobject (for file packages). Writing operations are usually initiated through the autosave featureFor reading operations, implement the
loadFromContents:ofType:error:method to receives anNSDataorNSFileWrapperobject and initialize the application's data structures with it.Implement change tracking to enable the autosaving feature. See “Change Tracking” for details.
When cloud services are enabled for a document, resolve conflicts between different versions of a document. See “Conflict Resolution and Error Handling” for details.
Both contentsForType:error: and loadFromContents:ofType:error: are typically called on the main queue.
If you have special requirements for reading and writing document data for which contentsForType:error: and loadFromContents:ofType:error: won’t suffice, you can override other methods of UIDocument. See “Advanced Overrides” for a discussion of these requirements and methods.
Change Tracking
To enable the autosaving feature of UIDocument, you must notify it when users make changes to a document. UIDocument periodically checks whether the hasUnsavedChanges method returns YES; if it does, it initiates the save operation for the document.
There are two primary ways to implement change tracking in your UIDocument subclass:
Call the methods of the
NSUndoManagerclass to implement undo and redo for the document. You can access the defaultNSUndoManagerobject from theundoManagerproperty. This is the preferred approach, especially for existing applications that already support undo and redo.Call the
updateChangeCount:method at the appropriate junctures in your code.
Conflict Resolution and Error Handling
A UIDocument object has a specific state at any moment in its life cycle. You can check the current state by querying the documentState property. And you can be notified of changes in the state of a document by observing the UIDocumentStateChangedNotification notification.
If your document is enabled for cloud services, it is important to check for conflicting versions of the document and attempt to resolve those conflicts. You do this by listening for the UIDocumentStateChangedNotification notification and then checking if the document state is UIDocumentStateInConflict. This state indicates that there are conflicting versions of the document, which you can access by calling the NSFileVersion class method unresolvedConflictVersionsOfItemAtURL:, passing in the document’s file URL. You should discretely notify users that conflicts exist and let them choose how they want to resolve the conflicts. Possible approaches for resolving conflicts are:
Displaying the conflicting versions, from which they can pick a version
Merging changes in the different versions
Choosing the document version with the most recent file modification date
Other document states indicate other errors. For example, UIDocumentStateClosed indicates an error in reading and UIDocumentStateSavingError indicates an error in saving or reverting a document. Your application is also notified of reading and writing errors through the success parameter passed into the completion handlers of openWithCompletionHandler:, closeWithCompletionHandler:, revertToContentsOfURL:completionHandler:, and saveToURL:forSaveOperation:completionHandler:.
You can also handle errors by calling or implementing the handleError:userInteractionPermitted: method; this method is called by the default implementations of openWithCompletionHandler: and saveToURL:forSaveOperation:completionHandler: when UIDocument encounters a reading or writing error, respectively. You can handle reading, saving, and reverting errors by informing the user and, if the situation permits, trying to recover from the error.
Advanced Overrides
If you application has special requirements for reading or writing document data, it can override methods of UIDocument other than loadFromContents:ofType:error: and contentsForType:error:. These requirements often include the following:
Incremental reading and writing of large data files
Override the
readFromURL:error:andwriteContents:toURL:forSaveOperation:originalContentsURL:error:methods, respectivelyCustom representations of document data (that is, not a
NSDataorNSFileWrapperobject)Override the
readFromURL:error:method (when reading document data) and thewriteContents:toURL:forSaveOperation:originalContentsURL:error:method (when writing document data).Performing actions before or after reading or writing data
Override
openWithCompletionHandler:andsaveToURL:forSaveOperation:completionHandler:A custom approach to safe-saving
Override the
writeContents:andAttributes:safelyToURL:forSaveOperation:error:method.Changing the file type of a document before it’s saved
Override the
savingFileTypemethod to return a file type other than the default (fileType). An example of this is an RTF document which, after a user adds an image to it, should be saved as an RTFD document.
If you override most of these methods be aware that all reading and writing of document data must be done on a background queue and must be coordinated with other attempts to read from and write to the same document file. Because of this, you should usually call the superclass implementation (super) as part of your override, and if you call other UIDocument methods you should usually invoke them in the block passed into a call of the performAsynchronousFileAccessUsingBlock: method. Read the method descriptions for the details.
Thread Safety Considerations
If you override any of the document-attribute properties (listed under “Accessing Document Attributes”) by overriding the related accessor methods, be aware that the UIKit framework can call these accessor methods on a background thread. Thus your overriding implementation must be thread safe.
Tasks
Initializing a Document Object
Accessing Document Attributes
-
fileURLproperty -
localizedNameproperty -
fileTypeproperty -
fileModificationDateproperty -
documentStateproperty
Writing Document Data
-
– closeWithCompletionHandler: -
– contentsForType:error: -
– saveToURL:forSaveOperation:completionHandler: -
– writeContents:andAttributes:safelyToURL:forSaveOperation:error: -
– writeContents:toURL:forSaveOperation:originalContentsURL:error: -
– savingFileType -
– fileAttributesToWriteToURL:forSaveOperation:error: -
– fileNameExtensionForType:saveOperation:
Reading Document Data
Accessing Document Files Asynchronously
Reverting a Document
Disabling and Enabling Editing
Tracking Changes and Autosaving
-
– hasUnsavedChanges -
– updateChangeCount: -
undoManagerproperty -
– changeCountTokenForSaveOperation: -
– updateChangeCountWithToken:forSaveOperation: -
– autosaveWithCompletionHandler:
Resolving Conflicts and Handling Errors
Properties
documentState
Returns the current state of the document.
Discussion
Whenever there is a change of document state, UIDocument stores the constant identifying the current state in this property. See “Document State” for descriptions of these constants. You can observe the UIDocumentStateChangedNotification notification to learn about changes in document state.
Availability
- Available in iOS 5.0 and later.
See Also
Declared In
UIDocument.hfileModificationDate
The date and time the document file was last modified.
Discussion
The modification date is updated by the openWithCompletionHandler:, saveToURL:forSaveOperation:completionHandler:, and revertToContentsOfURL:completionHandler: methods. Its value is nil if none of these methods has completed successfully at least once. If you override any of these methods, you should be sure to set this property in your implementation.
UIKit sets this property before it calls the completion handlers of the openWithCompletionHandler:, saveToURL:forSaveOperation:completionHandler:, and revertToContentsOfURL:completionHandler:. If, outside of these methods or their completion handlers, you want to wait for any pending file operations to complete before you access this property, you can call performAsynchronousFileAccessUsingBlock: and access the property value in the block parameter.
Availability
- Available in iOS 5.0 and later.
Declared In
UIDocument.hfileType
The file type of the document. (read-only)
Discussion
The file type is a uniform type identifier (UTI). UIKit derives the UTI from the filename-extension component of fileURL.
UIKit sets this property before it calls the completion handlers of the openWithCompletionHandler:, saveToURL:forSaveOperation:completionHandler:, and revertToContentsOfURL:completionHandler:. If, outside of these methods or their completion handlers, you want to wait for any pending file operations to complete before you access this property, you can call performAsynchronousFileAccessUsingBlock: and access the property value in the block parameter.
Availability
- Available in iOS 5.0 and later.
Declared In
UIDocument.hfileURL
The file URL with which the document was initialized. (read-only)
Discussion
The URL identifies the location of the document in the application sandbox. It includes the file extension, from which the file type is determined.
UIKit sets this property before it calls the completion handlers of the openWithCompletionHandler:, saveToURL:forSaveOperation:completionHandler:, and revertToContentsOfURL:completionHandler:. If, outside of these methods or their completion handlers, you want to wait for any pending file operations to complete before you access this property, you can call performAsynchronousFileAccessUsingBlock: and access the property value in the block parameter.
Availability
- Available in iOS 5.0 and later.
See Also
Declared In
UIDocument.hlocalizedName
The localized name of the document. (read-only)
Discussion
By default, UIKit obtains the value from the filename component of fileURL. You can override the getter accessor method of this property to provide a custom name for presentation to the user, such as in error strings. See “Subclassing Notes” in the class description for overriding advice.
UIKit sets this property before it calls the completion handlers of the openWithCompletionHandler:, saveToURL:forSaveOperation:completionHandler:, and revertToContentsOfURL:completionHandler:. If, outside of these methods or their completion handlers, you want to wait for any pending file operations to complete before you access this property, you can call performAsynchronousFileAccessUsingBlock: and access the property value in the block parameter.
Availability
- Available in iOS 5.0 and later.
Declared In
UIDocument.hundoManager
The undo manager for the document.
Discussion
This property holds the document's undo manager (an NSUndoManager object) or nil if this property has not been accessed or set. Accessing this property creates a default undo manager if a custom undo manager has not been set.
The undo manager for the document is registered as an observer of various NSUndoManager notifications so that it can call updateChangeCount: as the user makes undoable changes to the document. When a subclass sets this property and implements registers changes with it, it does not need to call updateChangeCount: directly or (more rarely) override hasUnsavedChanges.
Availability
- Available in iOS 5.0 and later.
Declared In
UIDocument.hInstance Methods
autosaveWithCompletionHandler:
Called by UIKit to initiate automatic saving of documents with unsaved changes.
Parameters
- completionHandler
A block with code to execute after automatic saving concludes. The block returns no value and has one parameter:
successYESif the autosaving operation succeeds, otherwiseNO.
The block is invoked on the calling queue.
Discussion
UIDocument periodically invokes this method to initiate a save operation if there are unsaved changes. You should not call this method directly. Subclasses can override it if they want to do special things with autosaving. The default implementation of this method invokes the hasUnsavedChanges method and, if that returns YES, it invokes the saveToURL:forSaveOperation:completionHandler: method.
This method should only be invoked for period-based saves. You may invoke it with the success parameter of the completion-handler parameter set to NO and return; this makes it safe to not actually save when autosaveWithCompletionHandler: is invoked. However, if you call saveToURL:forSaveOperation:completionHandler:, saving of document data must occur.
Availability
- Available in iOS 5.0 and later.
Declared In
UIDocument.hchangeCountTokenForSaveOperation:
Overridden to return a change token for a specific save operation.
Parameters
- saveOperation
A constant that indicates whether the save operation is writing a new file or overwriting an existing one. See “Document Save Operation” for descriptions of these constants.
Return Value
An object to use as a change-count token.
Discussion
To get autosaving capabilities for your documents, you must implement change tracking. Typically you do this by using an NSUndoManager object (assigned to undoManager property) to register changes or by calling the updateChangeCount: method every time the user makes a change; UIKit then automatically determines whether there are unsaved changes and returns the proper value from hasUnsavedChanges. If you take neither of these approaches (and you want the autosaving feature), you must implement this method as well as updateChangeCountWithToken:forSaveOperation: and hasUnsavedChanges.
You implement this particular method to return a change-count token that UIKit uses to encapsulate the history of document changes for a particular save operation. The token can be any object that represents the current change state of the document. This method is called at the start of the default implementation of the saveToURL:forSaveOperation:completionHandler: method. At the end of this default implementation, it calls the updateChangeCountWithToken:forSaveOperation: method, passing in the change-count token. You implement the latter method to compare the token with the one returned earlier; by doing so, you can determine if the document has acquired new unsaved changes between the start and end of an asynchronous write operation. You can then return the proper value from your override of hasUnsavedChanges.
Availability
- Available in iOS 5.0 and later.
Declared In
UIDocument.hcloseWithCompletionHandler:
Asynchronously closes the document after saving any changes.
Parameters
- completionHandler
A block with code to execute after the save-and-close operation concludes. The block returns no value and has one parameter:
successYESif any save operation succeeds, otherwiseNO.
The block is invoked on the main queue.
Discussion
You call this method to begin the sequence of method calls that saves a document safely and asynchronously. The file-system location of the document derives from the fileURL property. After the save operation concludes, the code in completionHandler is executed. In this code, you can close the document—for example, by removing the document’s view from the screen. Additionally, if the save operation did not succeed (success is NO), you can respond in an appropriate manner.
You typically would not override this method. The default implementation calls the autosaveWithCompletionHandler: method.
Availability
- Available in iOS 5.0 and later.
See Also
Declared In
UIDocument.hcontentsForType:error:
Overridden to return the document data to be saved.
Parameters
- typeName
The file type of the document, a Uniform Type Identifier (UTI). This string typically derives from the
fileTypeproperty. If you want to save the document under a different UTI, you can override thesavingFileTypemethod.- outError
If you cannot return document data, return by indirection an
NSErrorobject that encapsulates the reasons you can’t. Otherwise, ignore this parameter.
Return Value
The document data to be saved or nil if for some reason you cannot return document data. The returned object is typically either an instance of the NSData class for flat files or the NSFileWrapper class for file packages. If you return nil, you should also return an error object in outError.
If you return an object other than an NSData or NSFileWrapper object, you must override the writeContents:andAttributes:safelyToURL:forSaveOperation:error: or writeContents:toURL:forSaveOperation:originalContentsURL:error: method to handle the writing of data.
Discussion
Most subclasses of UIDocument override this method to provide UIKit with the document data for saving. If you want more control over the saving operation—for example, you want to perform incremental writing of data—override instead one of the lower-level data-writing methods such as writeContents:andAttributes:safelyToURL:forSaveOperation:error: or writeContents:toURL:forSaveOperation:originalContentsURL:error:. Note that these methods are called on a background thread.
This method is called on the queue on which saveToURL:forSaveOperation:completionHandler: was invoked (typically the main queue). The actual writing of data occurs on a background queue. The default implementation returns nil.
Availability
- Available in iOS 5.0 and later.
See Also
Declared In
UIDocument.hdisableEditing
Overridden to disable editing when it is unsafe to make changes to a document.
Discussion
Subclasses should override this method to prevent the user from editing the document when it is unsafe to do so, such as during a save-and-close or revert operation. When editing is safe again, UIKit class calls enableEditing. The default implementation of this method does nothing.
Availability
- Available in iOS 5.0 and later.
Declared In
UIDocument.henableEditing
Overridden to enable editing when it is safe again to make changes to a document.
Discussion
Subclasses should override this method to allow the user to edit the document when it is safe to do so. This method override should be paired with an override of disableEditing. The default implementation of this method does nothing.
Availability
- Available in iOS 5.0 and later.
Declared In
UIDocument.hfileAttributesToWriteToURL:forSaveOperation:error:
Returns a dictionary of file attributes to associate with the document file when writing or updating it.
Parameters
- url
A file URL locating the document in the application sandbox.
- saveOperation
A constant that indicates whether the document file is being written the first time or whether it is being overwritten. See “Document Save Operation” for details.
- outError
If you override this method and cannot write the document data for any reason, return by indirection an
NSErrorobject that encapsulates the reasons why you can’t. Otherwise, ignore this parameter.
Return Value
A dictionary of file attributes—for example, level of file protection and creation date. See NSFileManager Class Reference for more information about file attributes.
Discussion
The attributes are associated with a specific file type and save operation. You can override this method to return a dictionary of file attributes that are different than the default file attribute, which for new files is NSFileExtensionHidden.
The saveToURL:forSaveOperation:completionHandler: calls this method before executing asynchronous writing. It passes the dictionary into writeContents:andAttributes:safelyToURL:forSaveOperation:error: when it calls that method to write the document file.
Availability
- Available in iOS 5.0 and later.
Declared In
UIDocument.hfileNameExtensionForType:saveOperation:
Returns a file extension to append to the file URL of the document file being written.
Parameters
- typeName
A Uniform Type Identifier (UTI) that indicates the type of document (for example, PDF or HTML).
- saveOperation
A constant that indicates whether the document file is being written the first time or whether it is being overwritten. See “Document Save Operation” for details.
Return Value
A string to use as the file extension of the document file.
Discussion
The default implementation queries Launch Services to obtain the file extension matching the file (document) type. You can override this method to return a file extension that is different from the default extension. The default implementation of the saveToURL:forSaveOperation:completionHandler: method calls this method before it gets the document content and writes the document file to disk.
Availability
- Available in iOS 5.0 and later.
Declared In
UIDocument.hfinishedHandlingError:recovered:
Tells UIKit that you have finished handled the error.
Parameters
- error
An error object encapsulating information about the error.
- recovered
YESif you recovered from the error, otherwiseNO.
Discussion
This method is called by default when handling of an error (including any user interaction) is complete. Subclasses need to call this method only if they override handleError:userInteractionPermitted: and do not call the superclass implementation (super). If you override this method, you must call super.
Availability
- Available in iOS 5.0 and later.
Declared In
UIDocument.hhandleError:userInteractionPermitted:
Called or overridden to handle an error that occurs during an attempt to read, save, or revert a document.
Parameters
- error
An object encapsulating information about an error encountered in an attempt to open, save, or revert a document. The error domain is
NSCocoaErrorDomain. The error code is one of theenumconstants declared inFoundationErrors.h.- userInteractionPermitted
If
NO, no attempt is (or should be) made to present a modal view to the user. This value can beNOin cases such as when a save operation fails while the application is being suspended. If this parameter isYES, UIKit or your override may present error information to the user in a modal view and (optionally) allow the user to resolve the error.
Discussion
Typical subclasses do not need to call or override this method. Instead, they can observe the UIDocumentStateChangedNotification notification to be notified of changes in document state. In their notification handler, they can check the value of the documentState property and proceed accordingly. See “Conflict Resolution and Error Handling” for a discussion of this.
If you directly call any of the advanced reading and writing methods that have an error-object parameter (for example, writeContents:andAttributes:safelyToURL:forSaveOperation:error:) and that call returns an NSError object by indirection, you should call this method (handleError:userInteractionPermitted:), passing in the error object.
This method is called by the default implementations of openWithCompletionHandler: and saveToURL:forSaveOperation:completionHandler: when UIDocument encounters a reading or writing error, respectively.
If you override this method and do not invoke the superclass implementation (super), you are responsible for the following:
Calling
finishedHandlingError:recovered:when you are finished handling the error—for example, when the application does not require any additional user feedback about the error.Implementing
userInteractionNoLongerPermittedForError:to conclude error handling immediately. If userInteractionPermitted isNO, you should immediately handle the error and callfinishedHandlingError:recovered:within the context of thehandleError:userInteractionPermitted:
Availability
- Available in iOS 5.0 and later.
Declared In
UIDocument.hhasUnsavedChanges
Returns whether the document has any unsaved changes.
Return Value
YES if the document has unsaved changes, otherwise NO.
Discussion
The default implementation of autosaveWithCompletionHandler: initiates a save if this method returns YES. Typical subclasses do not need to override the hasUnsavedChanges method. To implement change tracking, they should instead use an NSUndoManager object (assigned to undoManager) to register changes or call updateChangeCount: every time the user makes a change; UIKit then automatically determines whether there are unsaved changes.
Availability
- Available in iOS 5.0 and later.
Declared In
UIDocument.hinitWithFileURL:
Returns a document object initialized with its file-system location.
Parameters
- url
A file URL identifying the location in the application sandbox where document data is to be written. Passing in
nilor an empty URL results in the throwing of anNSInvalidArgumentException.
Return Value
A UIDocument object or nil if the object could not be created.
Discussion
After you create a document object and no file exists for it yet, you should next call the saveToURL:forSaveOperation:completionHandler: to write the document to its file-system location in the application sandbox. If url locates an existing document file, call openWithCompletionHandler: after creating the document object. The second parameter of this method, the save operation constant, should be UIDocumentSaveForCreating when there is no document file yet. In the completion handler, if you want the document to be automatically synced with other devices and computers on which the application is installed, you should call the NSFileManager method setMobileSynchEnabled:forItemAtURL:destinationDirectory:replacementURL:error:.
Availability
- Available in iOS 5.0 and later.
See Also
Declared In
UIDocument.hloadFromContents:ofType:error:
Overridden to load the document data into the application’s data model.
Parameters
- contents
An object encapsulating the document data to load. This object is either an instance of the
NSDataclass (for flat files) or theNSFileWrapperclass (for file packages).- typeName
The file type of the document, a Uniform Type Identifier (UTI) based on the file extension of
fileURL. You can obtain the default value of the file type from thefileTypeproperty.- outError
If you cannot load the document data for any reason, return by indirection an
NSErrorobject that encapsulates the reasons you can’t. Otherwise, ignore this parameter.
Return Value
YES if you successfully load the document, NO otherwise.
Discussion
Most subclasses of UIDocument override this method to accept and load the data for a document. After UIDocument reads the document data from the file located at fileURL it calls the subclass, passing the data to the subclass in this method. This method is called by the readFromURL:error: method.
Availability
- Available in iOS 5.0 and later.
See Also
Declared In
UIDocument.hopenWithCompletionHandler:
Opens a document asynchronously.
Parameters
- completionHandler
A block with code to execute after the open operation concludes. The block returns no value and has one parameter:
successYESif the open operation succeeds, otherwiseNO.
The block is invoked on the main queue.
Discussion
You call this method to begin the sequence of method calls that opens and reads a document asynchronously. The method obtains the file-system location of the document from the fileURL property. After the open operation concludes, the code in completionHandler is executed.
You can override this method if you want custom document-opening behavior, but if you do it is recommended that you call the superclass implementation first (super). If you don’t call super, you should use the NSFileCoordinator class to implement coordinated reading. The default implementation sets up file coordination and then calls performAsynchronousFileAccessUsingBlock: to schedule the document-reading work for execution on a background queue. The queued task then calls readFromURL:error:.
Availability
- Available in iOS 5.0 and later.
See Also
Declared In
UIDocument.hperformAsynchronousFileAccessUsingBlock:
Schedules a document-reading or document-writing operation on a concurrent background queue.
Parameters
- block
A block that is invoked as the task to execute on the background queue. The block returns no value and takes no parameters.
Discussion
A typical UIDocument subclasses—that is, one that overrides contentsForType:error: and loadFromContents:ofType:error:— does not need to call this method.
The default implementations of saveToURL:forSaveOperation:completionHandler: and openWithCompletionHandler: call this method to serialize file access. If you override these methods and do not call super, you should call this method to serialize file access on a background queue. If you directly call the readFromURL:error: method, you should wrap that call in the block passed into performAsynchronousFileAccessUsingBlock:.
Availability
- Available in iOS 5.0 and later.
Declared In
UIDocument.hreadFromURL:error:
Reads the document data in a file at a specified location in the application sandbox.
Parameters
- url
A file URL that identifies the location of the document file in the application sandbox. This file URL is typically the one returned by the
fileURLproperty.- outError
If the document file cannot be read, returns by indirection an error object that encapsulates the reasons why the read operation failed.
Return Value
YES if the read operation succeeds, otherwise NO.
Discussion
Typical UIDocument subclasses should not need to call this method directly, especially if the entire file is read at once. The default implementation calls loadFromContents:ofType:error: on the queue on which openWithCompletionHandler: was called to provide the UIDocument subclass with the document data object.
Subclasses that want more control over the reading of the document file—for example, that want to read a large document file incrementally—can override this method. It is not necessary for these subclasses to call the superclass implementation (super).
Availability
- Available in iOS 5.0 and later.
Declared In
UIDocument.hrevertToContentsOfURL:completionHandler:
Reverts a document to the most recent document data stored on-disk.
Parameters
- url
A file URL locating the most recent version of the document file in the application’s sandbox.
- completionHandler
A block with code to execute after the reversion operation concludes. The block returns no value and has one parameter:
successYESif the reversion operation succeeds, otherwiseNO.
The block is invoked on the main queue.
Discussion
You call this method to discard all unsaved document modifications and replace the document's contents by reading the file or file package located by url. The default implementation brackets the reversion operation between disableEditing and enableEditingbecause the document should not accept user changes during this period. Subclasses that override this method must call the superclass implementation (super) or use the NSFileCoordinator class to initiate a coordinated read.
Availability
- Available in iOS 5.0 and later.
Declared In
UIDocument.hsaveToURL:forSaveOperation:completionHandler:
Saves document data to the specified location in the application sandbox.
Parameters
- url
The file URL identifying the location in the application sandbox to write the document data to. Typically, this is the URL obtained from the
fileURLproperty.- saveOperation
A constant that indicates whether the document file is being written the first time or whether it is being overwritten. See “Document Save Operation” for details.
- completionHandler
A block with code that is executed when the save operation concludes. The block returns no value and has one parameter:
successYESif the save operation succeeds, otherwiseNO.
This block is invoked on the calling queue.
Discussion
The default implementation of this method first calls the contentsForType:error: method synchronously on the calling queue to get the document data to save. Then it calls the writeContents:andAttributes:safelyToURL:forSaveOperation:error: method on a background queue to perform the actual writing of the data to disk.
If you override this method, it’s recommended that you first call the superclass implementation of the method (super). If you do not call super, you must do two things:
Implement coordinated writing by using the
NSFileCoordinatorclass.Call
performAsynchronousFileAccessUsingBlock:to put the save operation on a background queue. The block parameter of this method should callwriteContents:andAttributes:safelyToURL:forSaveOperation:error:.
Availability
- Available in iOS 5.0 and later.
See Also
Declared In
UIDocument.hsavingFileType
Returns the file type to use for saving a document.
Return Value
A Uniform Type Identifier (UTI) identifying a document type (for example, PDF or HTML).
Discussion
The default implementation returns the current file type obtained from the fileType property. The default implementation of the saveToURL:forSaveOperation:completionHandler: method appends an extension to the file URL that is based on the file type. So if you want to move the document to a new type and extension, you can override this method to supply that file type.
Availability
- Available in iOS 5.0 and later.
Declared In
UIDocument.hupdateChangeCount:
Update the change counter by indicating the kind of change.
Parameters
- change
A constant that indicates whether a change has been made, cleared, undone, or redone. See “Document Save Kind” for more information.
Discussion
Calling this method can affect the value returned by hasUnsavedChanges. You should not need to call method this if you access an NSUndoManager object from the undoManager property (or assign a custom one to it) and register changes with the undo manager.
Availability
- Available in iOS 5.0 and later.
Declared In
UIDocument.hupdateChangeCountWithToken:forSaveOperation:
Overridden to update the change count with reference to a change-count token passed in by UIKit.
Parameters
- changeCountToken
An object to use as a change-count token.
UIDocumentobtained this token earlier by callingchangeCountTokenForSaveOperation:.- saveOperation
A constant that indicates whether the save operation is writing a new file or overwriting an existing one. See “Document Save Operation” for descriptions of these constants.
Discussion
To get autosaving capabilities for your documents, you must implement change tracking. Typically you do this by using an NSUndoManager object (assigned to undoManager property) to register changes or by calling the updateChangeCount: method every time the user makes a change; UIKit then automatically determines whether there are unsaved changes and returns the proper value from hasUnsavedChanges. If you take neither of these approaches (and you want the autosaving feature), you must implement this method as well as changeCountTokenForSaveOperation: and hasUnsavedChanges.
You implement the changeCountTokenForSaveOperation: method to return a change-count token that UIKit uses to encapsulate the history of document changes for a particular save operation. The token can be any object that represents the current change state of the document. This method is called at the start of the default implementation of the saveToURL:forSaveOperation:completionHandler: method. At the end of this default implementation, UIDocument calls this method (updateChangeCountWithToken:forSaveOperation:), passing in the change-count token. You implement this method to compare the token with the one returned earlier; by doing so, you can determine if the document has acquired new unsaved changes between the start and end of an asynchronous write operation. You can then return the proper value from your override of hasUnsavedChanges.
Availability
- Available in iOS 5.0 and later.
Declared In
UIDocument.huserInteractionNoLongerPermittedForError:
Sent when it is no longer safe to proceed without immediately handling the error.
Parameters
- error
An error object encapsulating information about the error.
Discussion
UIKit calls this method when it is no longer safe to proceed without immediately handling the error, such as when the application is being suspended. Subclasses that override this method must immediately end error handling (including dismissing any interactive user interface) and call finishedHandlingError:recovered: before returning. It is only necessary to override this method if you override handleError:userInteractionPermitted: without invoking the superclass implementation (super).
Availability
- Available in iOS 5.0 and later.
Declared In
UIDocument.hwriteContents:andAttributes:safelyToURL:forSaveOperation:error:
Ensures that document data is written safely to a specified location in the application sandbox.
Parameters
- contents
The document data to write to disk. Typically, the data is encapsulated by an
NSDataobject (if a flat file) or anNSFileWrapperobject (if a file package).If the object encapsulating the document data is of some other type, you should override this method or
writeContents:toURL:forSaveOperation:originalContentsURL:error:to perform the actual writing of the data.- additionalFileAttributes
A dictionary of
NSFileManagerfile attributes to assign to the document file. The default implementation obtains these file attributes by callingfileAttributesToWriteToURL:forSaveOperation:error:.- url
The file URL specifying the location of the document file in the application sandbox.
- saveOperation
A constant that indicates whether the document file is being written the first time or whether it is being overwritten. See “Document Save Operation” for details.
- outError
If you override this method and cannot write the document data for any reason, return by indirection an
NSErrorobject that encapsulates the reasons why you can’t. Otherwise, ignore this parameter.
Return Value
YES if the write operation succeeds, otherwise NO.
Discussion
This method is responsible for writing the document file in a way that minimizes the danger of having the document data left in an inconsistent state because of an application crash, system crash, hardware failure, power outage, or similar reason. This default implementation of this method handles essential details that might change in future releases, so if you do override this method, you should be sure to invoke the superclass implementation (super) first.
You don’t need to call this method directly unless you are overriding the saveToURL:forSaveOperation:completionHandler: method or you are calling the superclass implementation of the method.
Availability
- Available in iOS 5.0 and later.
See Also
Declared In
UIDocument.hwriteContents:toURL:forSaveOperation:originalContentsURL:error:
Writes the document data to disk at the sandbox location indicated by a file URL.
Parameters
- contents
The document data to write to disk. Typically, the data is encapsulated by an
NSDataobject (if a flat file) or anNSFileWrapperobject (if a file package).If the object encapsulating the document data is of some other type, you should override this method or
writeContents:andAttributes:safelyToURL:forSaveOperation:error:to perform the actual writing of the data.- url
A file URL specifying the location of the document file in the application sandbox.
- saveOperation
A constant that indicates whether the document file is being written the first time or whether it is being overwritten. See “Document Save Operation” for details.
- originalContentsURL
A file URL specifying the previous location of the document file (if not
nil).- outError
If you override this method and cannot write the document data for any reason, return by indirection an
NSErrorobject that encapsulates the reasons why you can’t. Otherwise, ignore this parameter.
Return Value
YES if the write operation succeeds, otherwise NO.
Discussion
This method is called by the writeContents:toURL:forSaveOperation:originalContentsURL:error: to write the document data to disk. If you need access to the on-disk representation document while saving—for example, for doing incremental writes—you should override this method.
Availability
- Available in iOS 5.0 and later.
See Also
Declared In
UIDocument.hConstants
Document Save Kind
Constants for specifying the kind of change to a document.
enum {
UIDocumentChangeDone,
UIDocumentChangeUndone,
UIDocumentChangeRedone,
UIDocumentChangeCleared
};
typedef NSInteger UIDocumentChangeKind;
Constants
UIDocumentChangeDoneA change has beed made to the document.
Available in iOS 5.0 and later.
Declared in
UIDocument.h.UIDocumentChangeUndoneA change to the document has been undone.
Available in iOS 5.0 and later.
Declared in
UIDocument.h.UIDocumentChangeRedoneAn undone change to the document has been redone.
Available in iOS 5.0 and later.
Declared in
UIDocument.h.UIDocumentChangeClearedThe document is cleared of outstanding changes.
Available in iOS 5.0 and later.
Declared in
UIDocument.h.
Discussion
You specify one of these constants as a parameter of the updateChangeCount: method.
Declared In
UIDocument.hDocument Save Operation
Constants for specifying the type of save operation.
enum {
UIDocumentSaveForCreating,
UIDocumentSaveForOverwriting
};
typedef NSInteger UIDocumentSaveOperation;
Constants
UIDocumentSaveForCreatingThe document is being saved for the first time.
Available in iOS 5.0 and later.
Declared in
UIDocument.h.UIDocumentSaveForOverwritingThe document is being saved by overwriting the current version.
Available in iOS 5.0 and later.
Declared in
UIDocument.h.
Discussion
You specify one of these constants as a parameter in the following methods: saveToURL:forSaveOperation:completionHandler:, writeContents:andAttributes:safelyToURL:forSaveOperation:error:, writeContents:toURL:forSaveOperation:originalContentsURL:error:, fileAttributesToWriteToURL:forSaveOperation:error:, fileNameExtensionForType:saveOperation:changeCountTokenForSaveOperation:, and updateChangeCountWithToken:forSaveOperation:.
Declared In
UIDocument.hDocument State
The document state.
enum { UIDocumentStateNormal = 0,
UIDocumentStateClosed = 1 << 0,
UIDocumentStateInConflict = 1 << 1,
UIDocumentStateSavingError = 1 << 2,
UIDocumentStateEditingDisabled = 1 << 3 }; typedef NSInteger UIDocumentState;
Constants
UIDocumentStateNormalThe document is open, editing is enabled, and there are no conflicts or errors associated with it.
Available in iOS 5.0 and later.
Declared in
UIDocument.h.UIDocumentStateClosedThe document has either not been successfully opened, or has been since closed. The document properties might not be valid.
Available in iOS 5.0 and later.
Declared in
UIDocument.h.UIDocumentStateInConflictConflicts exist for the document file located at
fileURL. You can access these conflicting document versions by calling the otherVersionsOfItemAtURL: class method of theNSFileVersionclass. This method returns an array ofNSFileVersionobjects. You can then resolve the conflicting versions—for example, programmatically attempt to merge the versions or present the document versions to the user and request him or her to pick one.Available in iOS 5.0 and later.
Declared in
UIDocument.h.UIDocumentStateSavingErrorAn error has occurred that prevents the document from saving.
Available in iOS 5.0 and later.
Declared in
UIDocument.h.UIDocumentStateEditingDisabledThe document is busy and it is not currently safe for user edits. This state is set just before
UIDocumentcalls thedisableEditingmethod. It callsenableEditingwhen it becomes safe to edit again.UIDocumentalso sets this state when an error prevents the reverting of a document.Available in iOS 5.0 and later.
Declared in
UIDocument.h.
Discussion
UIDocument stores the current state of the document in the documentState property. You can observe the UIDocumentStateChangedNotification to learn about changes in the document state.
Declared In
UIDocument.hNotifications
UIDocumentStateChangedNotification
When handling this notification, you can check the value of the documentState property to see what the new state is and then proceed accordingly. There is no userInfo dictionary.
Availability
- Available in iOS 5.0 and later.
Declared In
UIDocument.h© 2011 Apple Inc. All Rights Reserved. (Last updated: 2011-10-12)