iOS Developer Library

Developer

Foundation Framework Reference NSFileCoordinator Class Reference

Options
Deployment Target:

On This Page
Language:

NSFileCoordinator

Inheritance


Conforms To


Import Statement


Swift

import Foundation

Objective-C

@import Foundation;

Availability


Available in iOS 5.0 and later.

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, but before your code to perform those actions executes, 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. A file presenter must balance calls to addFilePresenter: with a call to removeFilePresenter: before being released, even in a garbage-collected application. 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 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.

File Presenters and iOS

If your app enters the background with an active file presenter, any other processes that perform a coordinated read or write on the presented file can deadlock. To prevent this situation, call removeFilePresenter: to remove the file presenter in the applicationDidEnterBackground: method or in response to a UIApplicationDidEnterBackgroundNotification notification. Call addFilePresenter: to add the file presenter again in the applicationWillEnterForeground: method or in response to a UIApplicationWillEnterForegroundNotification notification.

File Coordinators and iOS

If your app goes to the background while in the middle of a coordinated read or write, your app may retain a lock on the file, and any other processes that attempt to perform a coordinated read or write on that file can deadlock. To prevent this situation, you should request additional background time to complete the operation by calling either the beginBackgroundTaskWithName:expirationHandler: or the beginBackgroundTaskWithExpirationHandler: method. If the request returns successfully, you can safely begin your coordinated read or write operation. If the request fails, you must cancel the read or write operation.

Once you have finished the coordinated read or write, you must call endBackgroundTask: to mark the end of your background task.

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.

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

    Declaration

    Swift

    init(filePresenter filePresenterOrNil: NSFilePresenter?)

    Objective-C

    - (instancetype)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 if the file presenter’s code and its notifications run on the same thread.

    Specifically, associating an NSFileCoordinator with an NSFilePresenter accomplishes the following:

    • Prevents the file coordinator from sending messages to the file presenter. This means that the file presenter won’t receive notifications about its own file operations. There is one exception: Messages about versions of the presented item being added, remove, or resolved during coordinated writing are sent to every relevant file presenter.

    • Prevents deadlocks that could occur when the file presenter performs a coordinated write operation in response to a savePresentedItemChangesWithCompletionHandler: message. Usually, coordinated writes must wait for all the coordinated read operations on the same file or directory. However, when a coordinated read forces a file presenter to write its contents, the write operation must proceed before the read operation can finish.

    • Prevents race conditions that could occur when the file presenter is sent a presentedItemDidMoveToURL: message and at the same time—but before this message is dequeued—the file presenter enqueues an operation using the old URL on a different queue. For the file coordinators to work effectively, however, the coordinator must be initialized on the same operation queue that the file presenter uses to receive its messages.

    • Allows the file coordination mechanism to gracefully handle file presenters that initially contain nil in the presentedItemURL property, but that can later contain a non-nil value after creating the item using a coordinated write operation. For example, AppKit uses this feature to instantiate new NSDocument objects immediately, instead of waiting until after the user saves the document.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 5.0 and later.

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

    Declaration

    Swift

    class func addFilePresenter(_ filePresenter: NSFilePresenter)

    Objective-C

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

    Be sure 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, even in a garbage-collected application.

    If you call this method while coordinated file operations are already under way in another process, 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. If you are going to read a file and then create a file presenter for that file, both actions should occur in the same coordinated read block. 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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 5.0 and later.

  • Unregisters the specified file presenter object.

    Declaration

    Swift

    class func removeFilePresenter(_ filePresenter: NSFilePresenter)

    Objective-C

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

    Call this method to unregister file presenters before those objects are deallocated, even in a garbage-collected application.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 5.0 and later.

  • Returns an array containing the currently registered file presenter objects.

    Declaration

    Swift

    class func filePresenters() -> [AnyObject]

    Objective-C

    + (NSArray *)filePresenters

    Return Value

    An array of objects that conform to the NSFilePresenter protocol.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 5.0 and later.

  • A string that uniquely identifies the file access that was performed by this file coordinator.

    Declaration

    Swift

    var purposeIdentifier: String

    Objective-C

    @property(copy) NSString *purposeIdentifier

    Discussion

    Coordinated reads and writes performed using the same purpose identifier never block each other, even if they occur in different processes. If you are coordinating file access on behalf of a file presenter, use initWithFilePresenter: and do not attempt to set a custom purpose identifier. Every file coordinator instance initialized with the same file presenter has the same purpose identifier.

    You may need to set a custom purpose identifier for the following reasons:

    • Your application has a File Provider extension. Any file coordination done on behalf of the File Provider needs to be done using the File Provider’s purpose identifier.

    • You have two separate subsystems that need to work together to perform a single high-level operation, and both subsystems perform their own coordinated reads or writes. Using the same purpose identifier in both subsystems prevents possible deadlocks between the two subsystems.

    When creating custom purpose identifiers, you can use a reverse DNS style string, such as com.example.MyApplication.MyPurpose, or a UUID string. You cannot use nil or zero-length strings.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 5.0 and later.

  • Performs a number of coordinated-read or -write operations asynchronously.

    Declaration

    Swift

    func coordinateAccessWithIntents(_ intents: [AnyObject], queue queue: NSOperationQueue, byAccessor accessor: (NSError!) -> Void)

    Objective-C

    - (void)coordinateAccessWithIntents:(NSArray *)intents queue:(NSOperationQueue *)queue byAccessor:(void (^)(NSError *error))accessor

    Parameters

    intents

    An array of file access intent objects, representing the individual read and write operations.

    queue

    The operation queue on which the accessor block is executed. The queue must not be nil.

    accessor

    A Block object containing the file operations corresponding to the file access intent objects in the intents array.

    The accessor block takes the following parameter:

    error

    If an error occurs while waiting for access, this parameter contains an NSError object that describes the problem. If access is successfully granted, it is set to nil, and you may perform the intended file access.

    Do not attempt to access the files if the error parameter contains a non-nil value.

    Discussion

    This method lets you asynchronously perform coordinated read or writes. You can specify any combination of individual read or write operations. The file coordinator waits asynchronously to get access to the files and then invokes the accessor block on the specified queue.

    If an error occurs while waiting for access, an error message is passed to the block. You must check the block’s error parameter before accessing any of the files. If the error parameter is set to nil, you can freely perform the read and write operations described by your intents. Otherwise, you may not access the files.

    Additionally, always use the URL property of your intent objects when accessing the files inside the accessor block. The system updates this property to account for any changes to the underlying files. For example, if the files are moved or renamed, the system updates this URL property to match.

    Your file coordinator has access to the files only until the accessor block returns. Do not dispatch tasks that continue to access these files onto other threads or queues. That can cause your app to access the files outside of file coordination, and could result in data corruption or data loss.

    In general, coordinated-read operations wait for coordinated-write operations on the same URL. Coordinated-write operations wait for both coordinated-read and coordinated-write operations on the same URL. Multiple coordinated reads can occur simultaneously without blocking each other.

    Performing a coordinated read or coordinated write on the contents of a file package is treated as a coordinated read or write to the package as a whole. In general, coordinated access to a directory that is not a file package is not affected by coordinated access to the directory’s contents. Similarly, accessing the contents does not affect the directory. However, if you make a coordinated write operation using the NSFileCoordinatorWritingForDeleting, NSFileCoordinatorWritingForMoving, or NSFileCoordinatorWritingForReplacing options, all coordinated access to the directory and its contents interact as if they were accessing the same URL.

    Coordinated reads and writes from the same file coordinator instance never block each other. However, if you make multiple, concurrent calls to coordinateAccessWithIntents:queue:byAccessor:, you risk deadlocking with another process that is similarly making multiple concurrent calls to its file coordinator. Wherever possible, invoke coordinateAccessWithIntents:queue:byAccessor: once, passing in multiple file access intent objects.

    Coordinated-read and -write operations also wait on any file presenters methods that are triggered as part of the coordinated access. Coordinated access triggers method calls on all the file presenters for the same URL—even on file presenters in other processes. There is only one exception: file coordinator never sends messages to the file presenter that was passed to its initWithFilePresenter: method.

    Coordinated reads trigger the following method calls:

    Coordinated writes trigger the following method calls:

    For both reading and writing, if there are multiple file presenters involved, the order in which the methods are called is undefined. If any of the file presenters signal an error, the coordinated access fails and the error is passed to the accessor block.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 8.0 and later.

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

    Declaration

    Swift

    func coordinateReadingItemAtURL(_ url: NSURL, options options: NSFileCoordinatorReadingOptions, error outError: NSErrorPointer, byAccessor reader: (NSURL!) -> Void)

    Objective-C

    - (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 the 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 a 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 or any item inside the file package and other writers are writing to other 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.

    When invoking these methods, declare a __block variable before the accessor block and initialize it to a value that signals failure, and then inside the accessor block set it to a value that indicates success. If the coordinated operation fails, then the accessor block never runs. The sentinel variable still holds a value that indicates failure, and the NSError out parameter contains a reference that describes the error.

    This method calls the relinquishPresentedItemToReader: method of any relevant file presenters. This method is called 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. Alternatively; 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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 5.0 and later.

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

    Declaration

    Swift

    func coordinateWritingItemAtURL(_ url: NSURL, options options: NSFileCoordinatorWritingOptions, error outError: NSErrorPointer, byAccessor writer: (NSURL!) -> Void)

    Objective-C

    - (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 to. If other objects or processes are acting on the item at the URL, the actual URL passed to writer parameter may be different from 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

    When invoking these methods, declare a __block variable before the accessor block and initialize it to a value that signals failure, and then inside the accessor block set it to a value that indicates success. If the coordinated operation fails, then the accessor block never runs. The sentinel variable still holds a value that indicates failure, and the NSError out parameter contains a reference that describes the error.

    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 or any item inside a file package and other writers are reading or writing to other items inside 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 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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 5.0 and later.

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

    Declaration

    Swift

    func coordinateReadingItemAtURL(_ readingURL: NSURL, options readingOptions: NSFileCoordinatorReadingOptions, writingItemAtURL writingURL: NSURL, options writingOptions: NSFileCoordinatorWritingOptions, error outError: NSErrorPointer, byAccessor readerWriter: (NSURL!, NSURL!) -> Void)

    Objective-C

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

    When invoking these methods, declare a __block variable before the accessor block and initialize it to a value that signals failure, and then inside the accessor block set it to a value that indicates success. If the coordinated operation fails, then the accessor block never runs. The sentinel variable still holds a value that indicates failure, and the NSError out parameter contains a reference that describes the error.

    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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 5.0 and later.

  • Initiates a write operation that involves a secondary write operation.

    Declaration

    Swift

    func coordinateWritingItemAtURL(_ url1: NSURL, options options1: NSFileCoordinatorWritingOptions, writingItemAtURL url2: NSURL, options options2: NSFileCoordinatorWritingOptions, error outError: NSErrorPointer, byAccessor writer: (NSURL!, NSURL!) -> Void)

    Objective-C

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

    When invoking these methods, declare a __block variable before the accessor block and initialize it to a value that signals failure, and then inside the accessor block set it to a value that indicates success. If the coordinated operation fails, then the accessor block never runs. The sentinel variable still holds a value that indicates failure, and the NSError out parameter contains a reference that describes the error.

    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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 5.0 and later.

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

    Declaration

    Swift

    func prepareForReadingItemsAtURLs(_ readingURLs: [AnyObject], options readingOptions: NSFileCoordinatorReadingOptions, writingItemsAtURLs writingURLs: [AnyObject], options writingOptions: NSFileCoordinatorWritingOptions, error outError: NSErrorPointer, byAccessor batchAccessor: ((() -> Void)!) -> Void)

    Objective-C

    - (void)prepareForReadingItemsAtURLs:(NSArray *)readingURLs options:(NSFileCoordinatorReadingOptions)readingOptions writingItemsAtURLs:(NSArray *)writingURLs options:(NSFileCoordinatorWritingOptions)writingOptions error:(NSError **)outError byAccessor:(void (^)(void (^completionHandler)(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.

    The block takes the following parameter:

    completionHandler

    A completion handler block. The batch accessor must call the completion handler when it has finished its read and write calls.

    Discussion

    Use this method to prepare the file coordinator for multiple read and write operations. 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.

    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. Instead, you must call the individual coordinated read and write methods from inside the batchAccessor block. You must then call the completion handler after all the coordinated reads and writes have completed. You can call the completion handler from any thread.

    Don’t simply pass this method all the URLs that are passed into the nested coordinate methods. Instead pass only the top-level files and directories involved in the operation. This method triggers messages to the file presenters of those items and to the file presenters of any items contained by those items.

    In most cases, passing the same reading and writing options to both this method and the contained coordination operations is redundant. For example, it is often appropriate to pass NSFileCoordinatorReadingWithoutChanges to nested read operations. This method has already triggered a call to savePresentedItemChangesWithCompletionHandler:. The individual read operations do not need to trigger additional calls.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 5.0 and later.

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

    Declaration

    Swift

    func itemAtURL(_ oldURL: NSURL, willMoveToURL newURL: NSURL)

    Objective-C

    - (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 no purpose. This method is nonfunctional in iOS.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 6.0 and later.

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

    Declaration

    Swift

    func itemAtURL(_ oldURL: NSURL, didMoveToURL newURL: NSURL)

    Objective-C

    - (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 for any of the item’s file presenters. If the item is a directory, this method calls presentedItemDidMoveToURL: on the file presenters for the item’s contents. Finally, it calls presentedSubitemAtURL:didMoveToURL: on the file presenter of any directory containing the item.

    You must call this method from a coordinated write block. Calling this method with the same URL in the oldURL and newURL parameters is harmless. This call must balance a call to itemAtURL:willMoveToURL:.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 5.0 and later.

  • Cancels any active file coordination calls.

    Declaration

    Swift

    func cancel()

    Objective-C

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 5.0 and later.

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

    Declaration

    Swift

    struct NSFileCoordinatorReadingOptions : RawOptionSetType { init(_ rawValue: UInt) init(rawValue rawValue: UInt) static var WithoutChanges: NSFileCoordinatorReadingOptions { get } static var ResolvesSymbolicLink: NSFileCoordinatorReadingOptions { get } static var ImmediatelyAvailableMetadataOnly: NSFileCoordinatorReadingOptions { get } static var ForUploading: NSFileCoordinatorReadingOptions { get } }

    Objective-C

    enum { NSFileCoordinatorReadingWithoutChanges = 1 << 0, NSFileCoordinatorReadingResolvesSymbolicLink = 1 << 1 NSFileCoordinatorReadingImmediatelyAvailableMetadataOnly = 1 << 2 NSFileCoordinatorReadingForUploading = 1 << 3 }; typedef NSUInteger NSFileCoordinatorReadingOptions;

    Constants

    • WithoutChanges

      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.

    • ResolvesSymbolicLink

      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). When you use this option, the system provides the resolved URL to the accessor block in place of the original URL.

      Available in iOS 5.0 and later.

    • ImmediatelyAvailableMetadataOnly

      NSFileCoordinatorReadingImmediatelyAvailableMetadataOnly

      Specify this constant if you want to read an item’s metadata without triggering a download.

      Specifying this option grants the coordinated read immediately (barring any conflicts with other readers, writers or file presenters on the same system), instead of waiting for the system to download the file’s contents and any additional metadata (for example, conflicting versions or thumbnails).

      Attempting to actually read the item’s contents during this coordinated read may give unexpected results or fail.

      Available in iOS 8.0 and later.

    • ForUploading

      NSFileCoordinatorReadingForUploading

      Specify this content when reading an item for the purpose of uploading its contents.

      When this option is used, the file coordinator creates a temporary snapshot of the item being read and relinquishes its claim on the original file. This action prevents the read operation from blocking other coordinated writes during a potentially long upload.

      If the item being read is a directory (such as a document package), then the snapshot is a new file containing the zipped contents of the directory. The URL passed to the accessor block points to the zipped file.

      When using this option, you may upload the document outside the accessor block. However, you should open a file descriptor to the file or relocate the file within the accessor block before doing so. The file coordinator unlinks the file after the block returns, rendering it inaccessible through the URL.

      Available in iOS 8.0 and later.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 5.0 and later.

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

    Declaration

    Swift

    struct NSFileCoordinatorWritingOptions : RawOptionSetType { init(_ rawValue: UInt) init(rawValue rawValue: UInt) static var ForDeleting: NSFileCoordinatorWritingOptions { get } static var ForMoving: NSFileCoordinatorWritingOptions { get } static var ForMerging: NSFileCoordinatorWritingOptions { get } static var ForReplacing: NSFileCoordinatorWritingOptions { get } static var ContentIndependentMetadataOnly: NSFileCoordinatorWritingOptions { get } }

    Objective-C

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

    Constants

    • ForDeleting

      NSFileCoordinatorWritingForDeleting

      When this constant is specified, the file coordinator calls the accommodatePresentedItemDeletionWithCompletionHandler: or accommodatePresentedSubitemDeletionAtURL:completionHandler: 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.

    • ForMoving

      NSFileCoordinatorWritingForMoving

      When specified for a directory item, the file coordinator waits for already running read and write operations of the directory’s contents, which 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. You can safely use it when moving file-system items without checking to see whether those items are files or directories.

      Available in iOS 5.0 and later.

    • ForMerging

      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.

    • ForReplacing

      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 method when the moving or creating an item should replace any item currently stored at that location. To avoid a race condition, use it regardless of whether an item is actually in the way before the writing begins. Do not use this method when simply updating the contents of the existing file.

      Available in iOS 5.0 and later.

    • ContentIndependentMetadataOnly

      NSFileCoordinatorWritingContentIndependentMetadataOnly

      Select this option when writing to change the file’s metadata only and not its contents.

      Any changes written to the item’s contents during this coordinated write may not be preserved or may fail. Changing metadata that is related to the item’s content is also not supported, and those changes may not be preserved. For example, changing the value of NSURLTagNamesKey is supported, but changing the value of NSURLContentModificationDateKey is not.

      Available in iOS 8.0 and later.

    Discussion

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 5.0 and later.