NSFileCoordinator Class Reference

Inherits from
Conforms to
Framework
/System/Library/Frameworks/Foundation.framework
Availability
Available in iOS 5.0 and later.
Declared in
NSFileCoordinator.h

Overview

The NSFileCoordinator class coordinates the reading and writing of files and directories among multiple processes and objects in the same process. You use instances of this class as-is to read from, write to, modify the attributes of, change the location of, or delete a file or directory. Before your code to perform those actions executes, though, the file coordinator lets registered file presenter objects perform any tasks that they might require to ensure their own integrity. For example, if you want to change the location of a file, other objects interested in that file need to know where you intend to move it so that they can update their references.

Objects that adopt the NSFilePresenter protocol must register themselves with the NSFileCoordinator class to be notified of any pending changes. They do this by calling the addFilePresenter: class method. In a managed memory application, a file presenter must balance calls to addFilePresenter: with a call to removeFilePresenter: prior to being released. (In a garbage-collected or ARC-based application, file presenters are removed automatically when they are finalized.) The file presenter class maintains a list of active file presenter objects in the current application and uses that list, plus the file coordinator classes in other processes, to deliver notifications to all of the objects interested in a particular item.

Instances of NSFileCoordinator are meant to be used on a per-file-operation basis, where a file operation is something like opening and reading the contents of a file or moving a batch of files and directories to a new location. There is no benefit to keeping a file coordinator object around past the length of the planned operation. In fact, because file coordinators retain file presenter objects, keeping one around could prevent the file presenter objects from being released in a timely manner.

For information about implementing a file presenter object to receive file-related notifications, see NSFilePresenter Protocol Reference.

Threading Considerations

Each file coordinator object you create should be used on a single thread only. If you need to coordinate file operations across multiple objects in different threads, each object should create its own file coordinator.

Tasks

Initializing a File Coordinator

Managing File Presenters

Coordinating File Operations

Class Methods

addFilePresenter:

Registers the specified file presenter object so that it can receive notifications.

+ (void)addFilePresenter:(id < NSFilePresenter >)filePresenter
Parameters
filePresenter

The file presenter object to register.

Discussion

This method registers the file presenter object process-wide. Thus, any file coordinator objects you create later automatically know about the file presenter object and know to message it when its file or directory is affected.

In a managed memory application—that is, an application that uses retain and release calls—it is your responsibility to balance calls to this method with a corresponding call to the removeFilePresenter: method. You must remove file presenters from the process-wide registry before the object is deallocated. If your application is garbage collected, file presenters automatically unregister themselves in their finalize method.

If you call this method while file operations are already underway in another thread, your file presenter may not receive notifications for that operation. To prevent missing such notifications, create a file coordinator, call its coordinateReadingItemAtURL:options:error:byAccessor: method, and register your file presenter object there. Synchronizing on the presented file or directory guarantees that when your block executes, all other objects have completed any tasks and you have sole access to the item.

Availability
  • Available in iOS 5.0 and later.
Declared In
NSFileCoordinator.h

filePresenters

Returns an array containing the currently registered file presenter objects.

+ (NSArray *)filePresenters
Return Value

An array of objects that conform to the NSFilePresenter protocol.

Availability
  • Available in iOS 5.0 and later.
Declared In
NSFileCoordinator.h

removeFilePresenter:

Unregisters the specified file presenter object.

+ (void)removeFilePresenter:(id < NSFilePresenter >)filePresenter
Parameters
filePresenter

The file presenter object to unregister. If the object is not currently registered, this method does nothing.

Discussion

If your application uses a managed memory model, you must call this method to unregister file presenters before those objects are deallocated. In a garbage-collected application, file presenters are unregistered automatically when they are finalized.

Availability
  • Available in iOS 5.0 and later.
Declared In
NSFileCoordinator.h

Instance Methods

cancel

Cancels any active file coordination calls.

- (void)cancel
Discussion

Use this method to cancel any active calls to coordinate the reading or writing of a file. If the block passed to the file coordination call has not yet been executed—perhaps because the file coordinator is still waiting for a response from other file presenters—the file coordinator method stops waiting for a response, does not execute its block, and returns an error object with the error code NSUserCancelledError. However, if the block is already being executed, the file coordinator method does not return until the block finishes executing.

You can call this method from any thread of your application and it returns immediately without waiting for the file coordinator object to respond. Thus, when this method returns, you cannot assume that the read or write operation occurred or did not occur. (In fact, it is possible for this method to return while the file coordinator is in the middle of executing a block.) If you want to know whether the operation actually occurred, you must track it yourself by setting a flag when the block starts executing or by using some other means.

Availability
  • Available in iOS 5.0 and later.
Declared In
NSFileCoordinator.h

coordinateReadingItemAtURL:options:error:byAccessor:

Initiates a read operation on a single file or directory using the specified options.

- (void)coordinateReadingItemAtURL:(NSURL *)url options:(NSFileCoordinatorReadingOptions)options error:(NSError **)outError byAccessor:(void (^)(NSURL *newURL))reader
Parameters
url

A URL identifying the file or directory to read. If other objects or processes are acting on the item at the URL, the actual URL passed to reader parameter may be different than the one in this parameter.

options

One of the reading options described in “NSFileCoordinatorReadingOptions.” If you pass 0 for this parameter, the savePresentedItemChangesWithCompletionHandler: method of relevant file presenters is called before your block executes.

outError

On input, a pointer to a pointer for an error object. If a file presenter encounters an error while preparing for this read operation, that error is returned in this parameter and the block in the reader parameter is not executed. If you cancel this operation before the reader block is executed, this parameter contains an error object on output.

reader

A Block object containing the file operations you want to perform in a coordinated manner. This block receives an NSURL object containing the URL of the item and returns no value. Always use the URL passed into the block instead of the value in the url parameter.

Discussion

You use this method to perform read-related operations on a file or directory in a coordinated manner. This method executes synchronously, blocking the current thread until the reader block finishes executing. Before executing that block, though, the file coordinator waits until other relevant file presenter objects finish in-progress actions. Similarly, your read operation may cause pending actions for other file presenters to wait until your operations are complete. Whether or not the file coordinator waits depends on whether the item being read is a file or directory and also depends on other related operations.

  • If the url parameter specifies a file:

    • This method waits for other writers of the exact same file to finish in-progress actions.

    • This method waits if the file is a file package and other writers are writing to items in the package directory.

    • This method does not wait for other readers of the file.

    • This method does not wait for writers that are manipulating the parent directory of the file, unless one of those writers specified the NSFileCoordinatorWritingForDeleting or NSFileCoordinatorWritingForMoving option.

  • If the url parameter specifies a directory:

    • This method waits if other write operations are occurring on the exact same directory.

    • This method does not wait if write operations are occurring on items inside the directory (but not on the directory itself).

    • This method does not wait for other readers of the directory.

    • This method does not wait for writers that are manipulating the parent directory of the directory, unless one of those writers specified the NSFileCoordinatorWritingForDeleting or NSFileCoordinatorWritingForMoving option.

This method calls the relinquishPresentedItemToReader: method of any relevant file presenters. This method is called both for file presenters in the current process and in other processes. Depending on the options you specify, other methods of the file presenters may also be called. When reading a file package directory, file presenter objects that are currently reading the contents of that file package also receive these notifications. All of the called methods must return successfully before the file coordinator executes your block. If multiple file presenters are operating on the item, the order in which those presenters are notified is undefined.

Do not nest calls to file coordinator methods inside the block you pass to this method. If you call this method or any of the other file coordination methods from inside your block, the file coordinator object throws an exception. If you want to perform a write operation from inside a read block, use the coordinateWritingItemAtURL:options:writingItemAtURL:options:error:byAccessor: method instead. If you want to perform a batch read operation on multiple files, use the prepareForReadingItemsAtURLs:options:writingItemsAtURLs:options:error:byAccessor: method.

If the device has not yet downloaded the file at the given URL, this method blocks (potentially for a long time) while the file is downloaded. If the file cannot be downloaded, this method fails. Alternately, use a metadata query to check for the NSMetadataUbiquitousItemIsDownloadedKey key, and then call the startDownloadingUbiquitousItemAtURL:error: method to download the file before trying to read it.

Availability
  • Available in iOS 5.0 and later.
Declared In
NSFileCoordinator.h

coordinateReadingItemAtURL:options:writingItemAtURL:options:error:byAccessor:

Initiates a read operation that contains a follow-up write operation.

- (void)coordinateReadingItemAtURL:(NSURL *)readingURL options:(NSFileCoordinatorReadingOptions)readingOptions writingItemAtURL:(NSURL *)writingURL options:(NSFileCoordinatorWritingOptions)writingOptions error:(NSError **)outError byAccessor:(void (^)(NSURL *newReadingURL, NSURL *newWritingURL))readerWriter
Parameters
readingURL

A URL identifying the file or directory to read. If other objects or processes are acting on the item at the URL, the actual URL passed to the block in the readerWriter parameter may be different than the one in this parameter.

readingOptions

One of the reading options described in “NSFileCoordinatorReadingOptions.” If you pass 0 for this parameter, the savePresentedItemChangesWithCompletionHandler: method of relevant file presenters is called before your block executes.

writingURL

A URL identifying the file or directory to write. If other objects or processes are acting on the item at the URL, the actual URL passed to the block in the readerWriter parameter may be different than the one in this parameter.

writingOptions

One of the writing options described in “NSFileCoordinatorWritingOptions.” The options you specify partially determine how file presenters are notified and how this file coordinator object waits to execute your block.

outError

On input, a pointer to a pointer for an error object. If a file presenter encounters an error while preparing for this operation, that error is returned in this parameter and the block in the readerWriter parameter is not executed. If you cancel this operation before the readerWriter block is executed, this parameter contains an error object on output.

readerWriter

A block object containing the read and write operations you want to perform in a coordinated manner. This block receives NSURL objects containing the URLs of the items to read and write and returns no value. Always use the URLs passed into the block instead of the values in the readingURL and writingURL parameters.

Discussion

You use this method to perform a read operation that might also contain a write operation that needs to be coordinated. This method executes synchronously, blocking the current thread until the readerWriter block finishes executing. When performing the write operation, you may call the coordinateWritingItemAtURL:options:error:byAccessor: method from your readerWriter block. This method does the canonical lock ordering that is required to prevent a potential deadlock of the file operations.

This method makes the same calls to file presenters, and has the same general wait behavior as the coordinateReadingItemAtURL:options:error:byAccessor: method.

Availability
  • Available in iOS 5.0 and later.
Declared In
NSFileCoordinator.h

coordinateWritingItemAtURL:options:error:byAccessor:

Initiates a write operation on a single file or directory using the specified options.

- (void)coordinateWritingItemAtURL:(NSURL *)url options:(NSFileCoordinatorWritingOptions)options error:(NSError **)outError byAccessor:(void (^)(NSURL *newURL))writer
Parameters
url

A URL identifying the file or directory to write. If other objects or processes are acting on the item at the URL, the actual URL passed to writer parameter may be different than the one in this parameter.

options

One of the writing options described in “NSFileCoordinatorWritingOptions.” The options you specify partially determine how file presenters are notified and how this file coordinator object waits to execute your block.

outError

On input, a pointer to a pointer for an error object. If a file presenter encounters an error while preparing for this write operation, that error is returned in this parameter and the block in the writer parameter is not executed. If you cancel this operation before the writer block is executed, this parameter contains an error object on output.

writer

A Block object containing the file operations you want to perform in a coordinated manner. This block receives an NSURL object containing the URL of the item and returns no value. Always use the URL passed into the block instead of the value in the url parameter.

Discussion

You use this method to perform write-related operations on a file or directory in a coordinated manner. This method executes synchronously, blocking the current thread until the writer block finishes executing. Before executing the block, though, the file coordinator waits until other relevant file presenter objects finish in-progress actions. Similarly, your write operation may cause pending actions for other file presenters to wait until your operations are complete. Whether or not the file coordinator waits depends on whether the item being written is a file or directory and also depends on other related operations.

  • If the url parameter specifies a file:

    • This method waits for other readers and writers of the exact same file to finish in-progress actions.

    • This method waits if the file is a file package and other writers are reading or writing items in the package directory.

    • This method does not wait for readers or writers that are manipulating the parent directory of the file, unless one of those writers specified the NSFileCoordinatorWritingForDeleting or NSFileCoordinatorWritingForMoving option.

  • If the url parameter specifies a directory:

    • This method waits if other read or write operations are occurring on the exact same directory.

    • This method does not wait if read or write operations are occurring on items inside the directory (but not on the directory itself).

    • This method does not wait for readers or writers that are manipulating the parent directory of the directory, unless one of those writers specified the NSFileCoordinatorWritingForDeleting or NSFileCoordinatorWritingForMoving option.

This method calls the relinquishPresentedItemToWriter: method of any relevant file presenters. This method is called both for file presenters in the current process and in other processes. Depending on the options you specify, other methods of the file presenters may also be called. When writing a file package directory, file presenter objects that are currently reading or writing the contents of that file package also receive these notifications. All of the called methods must return successfully before the file coordinator executes your block. If multiple file presenters are operating on the item, the order in which those presenters are notified is undefined.

With one exception, do not nest calls to file coordinator methods inside the block you pass to this method. You may call the coordinateReadingItemAtURL:options:error:byAccessor: method to read the file if you discover through modification-date checking that the contents of the file have changed. However, if you call this method from inside your block, the file coordinator object throws an exception.

Availability
  • Available in iOS 5.0 and later.
Declared In
NSFileCoordinator.h

coordinateWritingItemAtURL:options:writingItemAtURL:options:error:byAccessor:

Initiates a write operation that involves a secondary write operation.

- (void)coordinateWritingItemAtURL:(NSURL *)url1 options:(NSFileCoordinatorWritingOptions)options1 writingItemAtURL:(NSURL *)url2 options:(NSFileCoordinatorWritingOptions)options2 error:(NSError **)outError byAccessor:(void (^)(NSURL *newURL1, NSURL *newURL2))writer
Parameters
url1

A URL identifying the first file or directory to write. If other objects or processes are acting on the item at the URL, the actual URL passed to the block in the writer parameter may be different than the one in this parameter.

options1

One of the writing options described in “NSFileCoordinatorWritingOptions.”

url2

A URL identifying the other file or directory to write. If other objects or processes are acting on the item at the URL, the actual URL passed to the block in the writer parameter may be different than the one in this parameter.

options2

One of the writing options described in “NSFileCoordinatorWritingOptions.” The options you specify partially determine how file presenters are notified and how this file coordinator object waits to execute your block.

outError

On input, a pointer to a pointer for an error object. If a file presenter encounters an error while preparing for this operation, that error is returned in this parameter and the block in the writer parameter is not executed. If you cancel this operation before the writer block is executed, this parameter contains an error object on output.

writer

A Block object containing the write operations you want to perform in a coordinated manner. This block receives NSURL objects containing the URLs of the items to write and returns no value. Always use the URLs passed into the block instead of the values in the url1 and url2 parameters.

Discussion

You use this method to perform two write operations without the risk of those operations creating a deadlock. This method executes synchronously, blocking the current thread until the writer block finishes executing. You may call the coordinateWritingItemAtURL:options:error:byAccessor: method from your writer block. This method does the canonical lock ordering that is required to prevent a potential deadlock of the file operations.

This method makes the same calls to file presenters, and has the same general wait behavior as the coordinateWritingItemAtURL:options:error:byAccessor: method.

Availability
  • Available in iOS 5.0 and later.
Declared In
NSFileCoordinator.h

initWithFilePresenter:

Initializes and returns a file coordinator object using the specified file presenter.

- (id)initWithFilePresenter:(id < NSFilePresenter >)filePresenterOrNil
Parameters
filePresenterOrNil

The file presenter object that is initiating some action on its file or directory. This object is assumed to be performing the relevant file or directory operations and therefore does not receive notifications about those operations from the returned file coordinator object. This parameter may be nil.

Return Value

A file coordinator object to use to coordinate file-related operations.

Discussion

Specifying a file presenter at initialization time is strongly recommended, especially if the file presenter is initiating the file operation. Otherwise, the file presenter itself would receive notifications when it made changes to the file and would have to compensate for that fact. Receiving such notifications could also deadlock too if the file presenter’s code and its notifications run on the same thread.

Availability
  • Available in iOS 5.0 and later.
Declared In
NSFileCoordinator.h

itemAtURL:didMoveToURL:

Notifies relevant file presenters that the location of a file or directory changed.

- (void)itemAtURL:(NSURL *)oldURL didMoveToURL:(NSURL *)newURL
Parameters
oldURL

The old location of the file or directory.

newURL

The new location of the file or directory.

Discussion

If you move or rename a file or directory as part of a write operation, call this method to notify relevant file presenters that the change occurred. This method calls the presentedItemDidMoveToURL: method of any relevant file presenters.

You must call this method from a block invoked by the coordinateWritingItemAtURL:options:error:byAccessor: or coordinateWritingItemAtURL:options:writingItemAtURL:options:error:byAccessor: method. Calling this method with the same URL in the oldURL and newURL parameters is harmless.

Availability
  • Available in iOS 5.0 and later.
Declared In
NSFileCoordinator.h

itemAtURL:willMoveToURL:

Announces that your app is moving a file to a new URL.

- (void)itemAtURL:(NSURL *)oldURL willMoveToURL:(NSURL *)newURL
Parameters
oldURL

The old location of the file or directory.

newURL

The new location of the file or directory.

Discussion

This method is intended for apps that adopt App Sandbox.

Some apps need to rename files while saving them. For example, when a user adds an attachment to a rich text document, TextEdit changes the document’s filename extension from .rtf to .rtfd. In such a case, in a sandboxed app, you must call this method to declare your intent to rename a file without user approval.

After the renaming process succeeds, call the itemAtURL:didMoveToURL: method, with the same arguments, to provide your app with continued access to the file under its new name, while also giving up access to any file that appears with the old name.

If your OS X app is not sandboxed, this method serves to purpose. This method is nonfunctional in iOS.

Availability
  • Available in iOS 6.0 and later.
Declared In
NSFileCoordinator.h

prepareForReadingItemsAtURLs:options:writingItemsAtURLs:options:error:byAccessor:

Prepare to read or write from multiple files in a single batch operation.

- (void)prepareForReadingItemsAtURLs:(NSArray *)readingURLs options:(NSFileCoordinatorReadingOptions)readingOptions writingItemsAtURLs:(NSArray *)writingURLs options:(NSFileCoordinatorWritingOptions)writingOptions error:(NSError **)outError byAccessor:(void)batchAccessor
Parameters
readingURLs

An array of NSURL objects identifying the items you want to read.

readingOptions

One of the reading options described in “NSFileCoordinatorReadingOptions.” If you pass 0 for this parameter, the savePresentedItemChangesWithCompletionHandler: method of relevant file presenters is called before your block executes.

writingURLs

An array of NSURL objects identifying the items you want to write.

writingOptions

One of the writing options described in “NSFileCoordinatorWritingOptions.” The options you specify partially determine how file presenters are notified and how this file coordinator object waits to execute your block.

outError

On input, a pointer to a pointer for an error object. If a file presenter encounters an error while preparing for this operation, that error is returned in this parameter and the block in the writer parameter is not executed. If you cancel this operation before the batchAccessor block is executed, this parameter contains an error object on output.

batchAccessor

A Block object containing additional calls to methods of this class. This block receives a completion handler that it must execute when it has finished its read and write calls.

Discussion

You use this method to prepare the file coordinator for multiple read and write operations. This method executes synchronously, blocking the current thread until the batchAccessor block finishes executing. The block you provide for the batchAccessor parameter does not perform the actual operations itself but calls the coordinateReadingItemAtURL:options:error:byAccessor: and coordinateWritingItemAtURL:options:error:byAccessor: methods to perform them. The reason to call this method first is to improve performance when reading and writing large numbers of files or directories.

Because file coordination requires interprocess communication, it is much more efficient to batch changes to large numbers of files and directories than to change each item individually. The file coordinator uses the values in the readingURLs and writingURLs parameters together with reading and writing options to prepare any relevant file presenters for the upcoming operations. Specifically, it uses these parameters in the same way as the coordinateReadingItemAtURL:options:error:byAccessor: and coordinateWritingItemAtURL:options:error:byAccessor: methods to determine which file presenter methods to call.

Availability
  • Available in iOS 5.0 and later.
Declared In
NSFileCoordinator.h

Constants

NSFileCoordinatorReadingOptions

Options to use when reading the contents or attributes of a file or directory.

enum {
   NSFileCoordinatorReadingWithoutChanges = 1 << 0,
   NSFileCoordinatorReadingResolvesSymbolicLink = 1 << 1
};
typedef NSUInteger NSFileCoordinatorReadingOptions;
Constants
NSFileCoordinatorReadingWithoutChanges

Specify this constant if your code does not need other objects to save changes first. If you do not specify this constant, the savePresentedItemChangesWithCompletionHandler: method of relevant file presenters is called before your code reads the item.

Available in iOS 5.0 and later.

Declared in NSFileCoordinator.h.

NSFileCoordinatorReadingResolvesSymbolicLink

Specify this constant if you want an item that might be a symbolic link to resolve to the file pointed to by that link (instead of to the link itself). This option applies to the URL passed to the block that handles the actual reading of the item.

Available in iOS 5.0 and later.

Declared in NSFileCoordinator.h.

NSFileCoordinatorWritingOptions

Options to use when changing the contents or attributes of a file or directory.

enum {
   NSFileCoordinatorWritingForDeleting = 1 << 0,
   NSFileCoordinatorWritingForReplacing = 1 << 3,
   NSFileCoordinatorWritingForMoving = 1 << 1,
   NSFileCoordinatorWritingForMerging = 1 << 2
};
typedef NSUInteger NSFileCoordinatorWritingOptions;
Constants
NSFileCoordinatorWritingForDeleting

When this constant is specified, the file coordinator calls the accommodatePresentedItemDeletionWithCompletionHandler: method of relevant file presenters to give them a chance to make adjustments before the item is deleted.

Available in iOS 5.0 and later.

Declared in NSFileCoordinator.h.

NSFileCoordinatorWritingForReplacing

Specifies whether the act of writing to the file involves actually replacing the file with a different file (or directory). If the current file coordinator is waiting for another object to move or rename the file, this option treats the operation as the creation of a new file (instead of as the replacement of the old file); otherwise, this constant causes the same behavior as the NSFileCoordinatorWritingForDeleting constant. Use this option when the moving or creation of an item would cause the replacement of any existing item. Do not use it when simply updating the contents of the existing file.

Available in iOS 5.0 and later.

Declared in NSFileCoordinator.h.

NSFileCoordinatorWritingForMoving

When specified for a directory item, the file coordinator waits for already running read and write operations of the directory’s contents, that were themselves initiated through a file coordinator, to finish before moving the directory. Queued, but not executing, read and write operations on the directory’s contents wait until the move operation finishes.

This option has no effect on files.

Available in iOS 5.0 and later.

Declared in NSFileCoordinator.h.

NSFileCoordinatorWritingForMerging

When this constant is specified, the file coordinator calls the savePresentedItemChangesWithCompletionHandler: method of relevant file presenters to give them a chance to save their changes before your code makes its changes.

Available in iOS 5.0 and later.

Declared in NSFileCoordinator.h.

Discussion

You must specify only one constant at a time for a given write operation.