The NSPersistentDocument class is a subclass of NSDocument that is designed to easily integrate into the Core Data framework. It provides methods to access a document-wide NSManagedObjectContext object, and provides default implementations of methods to read and write files using the persistence framework. In a persistent document, the undo manager functionality is taken over by managed object context.
Language
- Swift
- Objective-C
SDK
- macOS 10.10+
Overview
Standard document behavior is implemented as follows:
Opening a document invokes
configurePersistentStoreCoordinator(for:ofType:modelConfiguration:storeOptions:)with the new URL, and adds a store of the default type (XML). Objects are loaded from the persistent store on demand through the document’s context.Saving a new document adds a store of the default type with the chosen URL and invokes save: on the context. For an existing document, a save just invokes
save()on the context.Save As for a new document simply invokes save. For an opened document, it migrates the persistent store to the new URL and invokes
save()on the context.Revert resets the document’s managed object context. Objects are subsequently loaded from the persistent store on demand, as with opening a new document.
By default an NSPersistentDocument instance creates its own ready-to-use persistence stack including managed object context, persistent object store coordinator and persistent store. There is a one-to-one mapping between the document and the backing object store.
You can customize the architecture of the persistence stack by overriding the methods NSPersistentDocument and configurePersistentStoreCoordinator(for:ofType:modelConfiguration:storeOptions:). You might wish to do this, for example, to specify a particular managed object model.
Important
NSPersistentDocument does not support some document behaviors:
File wrappers.
saveToOperationoperation type.Core Data does not support saving changes to a new document while maintaining the unsaved state in the current document.
Asynchronous saving.
NSPersistentDocumentdoes not support the asynchronous saving API ofNSDocumentbecause that API requires accessing the document’s state on multiple threads and that violates the requirements of theNSManagedObjectContextclass.