NSFilePresenter: What It Is, NSFileCoordinator Protocol and Tracking Methods

Author: IT Sectr Published: 2026-07-12 Reading time: 7 min

NSFilePresenter is a Foundation protocol that allows an object to receive notifications about file and directory changes in the iOS and macOS file system. The class implements the protocol methods and registers through NSFileCoordinator, after which the system automatically calls these methods during any operations with the tracked file. According to Apple Developer Documentation (2025), NSFilePresenter is used in applications with multi-threaded document access to prevent write conflicts. The protocol must be used in conjunction with NSFileCoordinator — only this ensures secure access coordination.

Key Takeaways

  • NSFilePresenter — a Foundation protocol for tracking file and directory changes in iOS and macOS.
  • NSFileCoordinator — a mandatory companion class that manages access and calls delegate methods.
  • accommodatePresentedItemDeletion — a method for handling deletion of the tracked file with cancellation capability.
  • presentedItemDidChange — called when the contents of a file or directory change.
  • presentedItemURL — a required property that returns the URL of the tracked file.

What Is NSFilePresenter?

NSFilePresenter is a Foundation protocol designed for tracking file and directory changes in Apple operating systems. The protocol defines a set of methods that the observer object implements to receive file system event notifications.

The main purpose of the protocol is to provide safe file access in multi-threaded scenarios. In iOS and macOS, multiple processes and threads can access the same file simultaneously through NSFileCoordinator, and NSFilePresenter ensures that each participant receives the latest data state.

The protocol has been included in Foundation since iOS 5.0 and macOS 10.7. It is used in applications working with documents, databases, and any files that may be modified simultaneously from different sources — for example, during iCloud synchronization or collaborative editing.

Where NSFilePresenter Is Used

Document-based applications — the primary area of NSFilePresenter usage. Applications working with UIDocument or NSDocument automatically register themselves as presenters through NSFileCoordinator. This allows correctly handling conflicts when editing the same file from multiple windows or devices.

iCloud synchronization — the second key scenario. When a file is modified on one device, iCloud syncs it across all connected devices. NSFilePresenter notifies the application of these changes, allowing timely interface updates.

Multi-threaded editors — the third scenario. In applications where background queues load and save data simultaneously with user work, NSFilePresenter prevents race conditions during file writing and reading.

How Does NSFilePresenter Work?

The working mechanism of NSFilePresenter is based on the delegation model: the object implements protocol methods, registers through NSFileCoordinator, and receives calls whenever the tracked file changes. The system itself determines when a change occurs and which methods to invoke.

The process begins when the object creates an instance of NSFileCoordinator and calls the coordinator’s method, passing the file URL. The coordinator checks if any presenters are registered for this URL. If yes, it blocks read or write access and notifies presenters of the upcoming change through protocol methods.

After the operation completes, the coordinator releases the lock and calls final notifications. Notably, the presenter does not control the execution flow — it only reacts to events. NSFileCoordinator is fully responsible for coordination.

Notification Lifecycle

Preparation phase — before executing an operation, the coordinator calls accommodatePresentedItemDeletion or accommodatePresentedSubitemDeletion. The presenter can handle the situation or cancel the operation by returning an error. This phase allows the application to properly finish working with the file before it is modified.

Notification phase — after the operation completes, the coordinator calls presentedItemDidChange or presentedSubitemDidChange. The presenter receives a signal that the file has changed and can re-read its contents. For file relocation, presentedItemDidMoveToURL is called with the new location.

Completion phase — the coordinator releases all locks and frees resources. The presenter can continue working with updated data. All three phases execute synchronously in a single thread, so protocol methods must execute quickly without lengthy I/O operations.

Main Protocol Methods

The NSFilePresenter protocol contains several required and optional methods. The only required property is presentedItemURL, which returns the URL of the tracked file or directory. Without this property, the object cannot be registered as a presenter.

Required Methods

presentedItemURL — a URL? type property that must return the path to the tracked file. If the object tracks multiple files, the property returns the URL of the primary item. For directories, it returns the directory URL.

presentedItemDidChange — called after the tracked file’s contents change. In this method, the presenter updates its internal state and reloads data. This method does not receive information about what exactly changed — only the fact of change.

Optional Methods

accommodatePresentedItemDeletion — called before file deletion. The presenter can save the current state, close file descriptors, or cancel the operation by returning an NSError. If the method returns an error, the deletion operation is not performed.

presentedItemDidMoveToURL — called after file relocation or renaming. The method receives the new URL, and the presenter must update the file reference. Without implementing this method, the presenter will continue pointing to the old, non-existent path.

NSFilePresenter and NSFileCoordinator

NSFileCoordinator and NSFilePresenter are an inseparable pair. NSFileCoordinator manages file access and calls presenter methods. The presenter does not work directly with the file system — all operations go through the coordinator, which guarantees atomicity of changes.

The coordinator registers the presenter via the addFilePresenter method of the NSFileCoordinator class. After registration, the presenter starts receiving notifications. Removal is done via removeFilePresenter. The system holds a weak reference to the presenter, so the object must remain alive throughout the tracking period.

According to Apple WWDC 2022, NSFileCoordinator uses a kernel-level coordination mechanism, ensuring minimal latency during locking. In the latest iOS versions, the coordinator is optimized for working with Sandbox and app extensions.

Coordination Rules

Intention — each read or write operation must be wrapped in a coordination block: reading via coordinateReadingItemAtURL, writing via coordinateWritingItemAtURL. The coordinator automatically locks the file for other participants during block execution.

Batch coordination — for operations involving multiple files, batch coordination is used. The coordinator atomically locks all specified files, performs the operation, and releases locks. This is critically important when moving or copying document sets.

Implementation Example

Let’s create a DocumentPresenter class that implements the NSFilePresenter protocol and tracks changes to a document file. The class contains a reference to the file, internal data, and a validity flag.

swift
import Foundation

class DocumentPresenter: NSObject, NSFilePresenter {
    var presentedItemURL: URL? {
        return self.fileURL
    }

    var presentedItemOperationQueue: OperationQueue {
        return self.queue
    }

    private let fileURL: URL
    private let queue = OperationQueue()

    func presentedItemDidChange() {
        self.reloadData()
    }

    func accommodatePresentedItemDeletion() throws {
        try self.saveCurrentState()
    }

    private func reloadData() {
        let coordinator = NSFileCoordinator(filePresenter: self)
        var error: NSError?
        coordinator.coordinate(readingItemAt: self.fileURL,
                               options: [],
                               error: &error)
        { readURL in
            guard let data = try? Data(contentsOf: readURL)
            else { return }
            self.processData(data)
        }
    }

    private func processData(_: Data) {
        // Document data processing
    }
}

The class implements presentedItemDidChange for reloading data when the file changes and accommodatePresentedItemDeletion for saving state before deletion. The operation queue ensures that all notifications are processed sequentially.

Presenter registration is done via NSFileCoordinator.addFilePresenter when opening a document. It is important to pass the correct reading options to the coordinator — withoutChanges for non-modifying operations or immediatelyAvailable for scenarios requiring immediate access.

Common Mistakes

The first common mistake is lack of presentedItemOperationQueue implementation. If you don’t specify a queue, notifications may arrive on an arbitrary thread, causing data races. Always use a serial OperationQueue for processing notifications.

The second mistake is blocking in presenter methods. Protocol methods are called synchronously from the coordinator. If the presenter performs a lengthy operation (database write, network request), it blocks the coordinator for all other participants. Move heavy operations to background queues.

The third mistake is ignoring accommodatePresentedItemDeletion. If the presenter does not implement this method and does not return an error, the file may be deleted without saving the current state. Always save data in this method if it hasn’t been written to disk yet.

The fourth mistake is recursive coordination. When the presenter inside a notification method calls the coordinator again for the same file, a deadlock occurs. Check the isCoordinatedOperation flag before starting coordination inside a handler.

MistakeConsequenceSolution
No operation queueData race in multi-threadingSpecify OperationQueue
Blocking in methodsCoordinator hangMove to background thread
Ignoring deletionData loss on deletionImplement saving
Recursive coordinationApplication deadlockisCoordinatedOperation flag

Frequently Asked Questions

Why Do We Need NSFilePresenter if NSFileHandle Exists?

NSFileHandle is a low-level interface for reading and writing data that does not provide notification mechanisms for changes from other processes. NSFilePresenter works at the coordination level: it receives events from the system whenever a file changes, regardless of the source — another thread, process, or iCloud.

Is It Mandatory to Use NSFileCoordinator with NSFilePresenter?

Yes. NSFilePresenter has no meaning without NSFileCoordinator. The presenter only defines handler methods, while the coordinator manages locks and calls these methods. If you use NSFilePresenter without a coordinator, notifications will not be delivered.

Can One Object Be a Presenter for Multiple Files?

It can, but with limitations. The presentedItemURL property returns only one URL, so for tracking multiple files, the NSFilePresenter protocol is used with additional methods for sub-items. An alternative is to create a separate presenter instance for each file.

How Does NSFilePresenter Work with Sandbox in iOS?

NSFilePresenter is fully compatible with the iOS sandbox. The application can only track files within its own container. For accessing files from other applications, App Groups or Security-Scoped Bookmarks are used. The coordinator operates within sandbox permissions.

What to Do If presentedItemDidChange Is Called Too Often?

Use debounce or throttle inside the presentedItemDidChange method. Create a timer with a 0.3–0.5 second delay and reset it on each new call. After stabilization, perform data reload. This prevents multiple processing of a single change batch.

Summary

  • NSFilePresenter — a Foundation protocol for receiving file change notifications in iOS and macOS, working exclusively in conjunction with NSFileCoordinator.
  • Required property presentedItemURL — without it, the object cannot be registered as a presenter and will not receive notifications.
  • Main method presentedItemDidChange is called after any file content change — use it to reload data.
  • accommodatePresentedItemDeletion allows properly handling file deletion and saving the current application state.
  • NSFileCoordinator manages locks and guarantees atomicity of operations — without a coordinator, the presenter is useless.
  • Common mistakes include missing operation queue, blocking in methods, and recursive coordination — these should be avoided through proper design.
  • Debounce presentedItemDidChange on frequent calls — use a timer to batch changes before reloading.

We will develop a mobile application turnkey

IT Sectr creates iOS and Android applications for startups and businesses since 2017. We will advise you and propose the best solution.

Discuss the project

Read also