Class: UIDocument
Overview
The UIDocument class is an abstract base class for managing the data of documents.
Direct Known Subclasses
Instance Attribute Summary (collapse)
-
- documentState
readonly
Returns the current state of the document.
-
- fileModificationDate
The date and time the document file was last modified.
-
- fileType
readonly
The file type of the document.
-
- fileURL
readonly
The file URL with which the document was initialized.
-
- localizedName
readonly
The localized name of the document.
-
- undoManager
The undo manager for the document.
Instance Method Summary (collapse)
-
- autosaveWithCompletionHandler:
Called by UIKit to initiate automatic saving of documents with unsaved changes.
-
- changeCountTokenForSaveOperation:
Overridden to return a change token for a specific save operation.
-
- closeWithCompletionHandler:
Asynchronously closes the document after saving any changes.
-
- contentsForType:error:
Overridden to return the document data to be saved.
-
- disableEditing
Overridden to disable editing when it is unsafe to make changes to a document.
-
- enableEditing
Overridden to enable editing when it is safe again to make changes to a document.
-
- fileAttributesToWriteToURL:forSaveOperation:error:
Returns a dictionary of file attributes to associate with the document file when writing or updating it.
-
- fileNameExtensionForType:saveOperation:
Returns a file extension to append to the file URL of the document file being written.
-
- finishedHandlingError:recovered:
Tells UIKit that you have finished handled the error.
-
- handleError:userInteractionPermitted:
Called or overridden to handle an error that occurs during an attempt to read, save, or revert a document.
-
- hasUnsavedChanges
Returns whether the document has any unsaved changes.
-
- initWithFileURL:
Returns a document object initialized with its file-system location.
-
- loadFromContents:ofType:error:
Overridden to load the document data into the application’s data model.
-
- openWithCompletionHandler:
Opens a document asynchronously.
-
- performAsynchronousFileAccessUsingBlock:
Schedules a document-reading or document-writing operation on a concurrent background queue.
-
- readFromURL:error:
Reads the document data in a file at a specified location in the application sandbox.
-
- revertToContentsOfURL:completionHandler:
Reverts a document to the most recent document data stored on-disk.
-
- saveToURL:forSaveOperation:completionHandler:
Saves document data to the specified location in the application sandbox.
-
- savingFileType
Returns the file type to use for saving a document.
-
- updateChangeCount:
Update the change counter by indicating the kind of change.
-
- updateChangeCountWithToken:forSaveOperation:
Overridden to update the change count with reference to a change-count token passed in by UIKit.
-
- userInteractionNoLongerPermittedForError:
Sent when it is no longer safe to proceed without immediately handling the error.
-
- writeContents:andAttributes:safelyToURL:forSaveOperation:error:
Ensures that document data is written safely to a specified location in the application sandbox.
-
- writeContents:toURL:forSaveOperation:originalContentsURL:error:
Writes the document data to disk at the sandbox location indicated by a file URL.
Methods inherited from NSObject
#!, #!=, #!~, #, #==, #===, #=~, #Rational, #__callee__, #__method__, #__send__, #__type__, `, alloc, allocWithZone:, #autoContentAccessingProxy, autoload, autoload?, autorelease_pool, #awakeAfterUsingCoder:, binding, block_given?, caller, cancelPreviousPerformRequestsWithTarget:, cancelPreviousPerformRequestsWithTarget:selector:object:, catch, class, classFallbacksForKeyedArchiver, #classForCoder, #classForKeyedArchiver, classForKeyedUnarchiver, #clone, conformsToProtocol:, #copy, copyWithZone:, #dealloc, #define_singleton_method, description, display, #doesNotRecognizeSelector:, #dup, #enum_for, #eql?, #equal?, #extend, fail, #finalize, format, #forwardInvocation:, #forwardingTargetForSelector:, framework, #freeze, #frozen?, getpass, gets, global_variables, #init, initialize, #initialize_clone, #initialize_copy, #initialize_dup, #inspect, instanceMethodForSelector:, instanceMethodSignatureForSelector:, #instance_eval, #instance_exec, #instance_of?, #instance_variable_defined?, #instance_variable_get, #instance_variable_set, #instance_variables, instancesRespondToSelector:, isSubclassOfClass:, #is_a?, iterator?, #kind_of?, lambda, load, load_bridge_support_file, load_plist, local_variables, loop, #method, #methodForSelector:, #methodSignatureForSelector:, #methods, #mutableCopy, mutableCopyWithZone:, new, #nil?, open, p, #performSelector:onThread:withObject:waitUntilDone:, #performSelector:onThread:withObject:waitUntilDone:modes:, #performSelector:withObject:afterDelay:, #performSelector:withObject:afterDelay:inModes:, #performSelectorInBackground:withObject:, #performSelectorOnMainThread:withObject:waitUntilDone:, #performSelectorOnMainThread:withObject:waitUntilDone:modes:, print, printf, #private_methods, proc, #protected_methods, #public_method, #public_methods, #public_send, putc, puts, raise, rand, readline, readlines, #replacementObjectForCoder:, #replacementObjectForKeyedArchiver:, require, resolveClassMethod:, resolveInstanceMethod:, #respond_to?, #respond_to_missing?, select, #send, setVersion:, #singleton_methods, sprintf, srand, superclass, #taint, #tainted?, #tap, test, throw, #to_plist, #to_s, trace_var, trap, #trust, #untaint, untrace_var, #untrust, #untrusted?, version
Constructor Details
This class inherits a constructor from NSObject
Dynamic Method Handling
This class handles dynamic methods through the method_missing method in the class NSObject
Instance Attribute Details
- (UIDocumentState) documentState (readonly)
Returns the current state of the document. 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.
- (NSDate) fileModificationDate
The date and time the document file was last modified. 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.
- (String) fileType (readonly)
The file type of the document. (read-only) 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.
- (NSURL) fileURL (readonly)
The file URL with which the document was initialized. (read-only) 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.
- (String) localizedName (readonly)
The localized name of the document. (read-only) 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.
- (NSUndoManager) undoManager
The undo manager for the document. 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.
Instance Method Details
- (Object) autosaveWithCompletionHandler(completionHandler)
Called by UIKit to initiate automatic saving of documents with unsaved changes. 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.
- (Object) changeCountTokenForSaveOperation(saveOperation)
Overridden to return a change token for a specific save operation. 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.
- (Object) closeWithCompletionHandler(completionHandler)
Asynchronously closes the document after saving any changes. 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.
- (Object) contentsForType(typeName, error:outError)
Overridden to return the document data to be saved. 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.
- (Object) disableEditing
Overridden to disable editing when it is unsafe to make changes to a document. 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.
- (Object) enableEditing
Overridden to enable editing when it is safe again to make changes to a document. 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.
- (Hash) fileAttributesToWriteToURL(url, forSaveOperation:saveOperation, error:outError)
Returns a dictionary of file attributes to associate with the document file when writing or updating it. 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.
- (String) fileNameExtensionForType(typeName, saveOperation:saveOperation)
Returns a file extension to append to the file URL of the document file being written. 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.
- (Object) finishedHandlingError(error, recovered:recovered)
Tells UIKit that you have finished handled the error. 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.
- (Object) handleError(error, userInteractionPermitted:userInteractionPermitted)
Called or overridden to handle an error that occurs during an attempt to read, save, or revert a document. 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 is NO, you should immediately handle the error and call finishedHandlingError:recovered: within the context of the handleError:userInteractionPermitted:
- (Boolean) hasUnsavedChanges
Returns whether the document has any unsaved changes. 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.
- (Object) initWithFileURL(url)
Returns a document object initialized with its file-system location. 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:.
- (Boolean) loadFromContents(contents, ofType:typeName, error:outError)
Overridden to load the document data into the application’s data model. 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.
- (Object) openWithCompletionHandler(completionHandler)
Opens a document asynchronously. 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:.
- (Object) performAsynchronousFileAccessUsingBlock(block)
Schedules a document-reading or document-writing operation on a concurrent background queue. 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:.
- (Boolean) readFromURL(url, error:outError)
Reads the document data in a file at a specified location in the application sandbox. 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).
- (Object) revertToContentsOfURL(url, completionHandler:completionHandler)
Reverts a document to the most recent document data stored on-disk. 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.
- (Object) saveToURL(url, forSaveOperation:saveOperation, completionHandler:completionHandler)
Saves document data to the specified location in the application sandbox. 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 NSFileCoordinator class. Call performAsynchronousFileAccessUsingBlock: to put the save operation on a background queue. The block parameter of this method should call writeContents:andAttributes:safelyToURL:forSaveOperation:error:.
- (String) savingFileType
Returns the file type to use for saving a document. 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.
- (Object) updateChangeCount(change)
Update the change counter by indicating the kind of change. 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.
- (Object) updateChangeCountWithToken(changeCountToken, forSaveOperation:saveOperation)
Overridden to update the change count with reference to a change-count token passed in by UIKit. 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.
- (Object) userInteractionNoLongerPermittedForError(error)
Sent when it is no longer safe to proceed without immediately handling the error. 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).
- (Boolean) writeContents(contents, andAttributes:additionalFileAttributes, safelyToURL:url, forSaveOperation:saveOperation, error:outError)
Ensures that document data is written safely to a specified location in the application sandbox. 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.
- (Boolean) writeContents(contents, toURL:url, forSaveOperation:saveOperation, originalContentsURL:originalContentsURL, error:outError)
Writes the document data to disk at the sandbox location indicated by a file URL. 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.