UIManagedDocument Class Reference
| Inherits from | |
| Conforms to | |
| Framework | /System/Library/Frameworks/UIKit.framework |
| Availability | Available in iOS 5.0 and later. |
| Companion guide | |
| Declared in | UIManagedDocument.h |
Overview
UIManagedDocument is a concrete subclass of UIDocument that integrates with Core Data. When you initialize a managed document, you specify the URL for the document location. The document object then creates a Core Data stack to use to access the document’s persistent store using managed object model from the application’s main bundle.
UIManagedDocument performs all the basic set-up you need for Core Data, and in some cases you may use instances of UIManagedDocument directly (without a need to subclass). You can supply configuration options for the creation of the coordinator using persistentStoreOptions, and for the model using modelConfiguration. You can also perform additional customization by creating a subclass of UIManagedDocument:
Override
persistentStoreNameto customize the name of the persistent store file inside the document’s file package.Override
managedObjectModelto customize creation of the managed object model.You do this if, for example, your application supports multiple document types, each of which uses a different model. You want to ensure that the models are not merged for each document class.
Override
persistentStoreTypeForFileType:to customize the type of persistent store used by a document.Override
configurePersistentStoreCoordinatorForURL:ofType:modelConfiguration:storeOptions:error:to customize the loading or creation of a persistent store.
Creating a Managed Document
You create a managed document object using initWithFileURL:; if you want, you can then configure the document before you use its managed object context. Typically you might set the persistent store options, as illustrated in this example:
NSURL *docURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"FirstDocument"]; |
doc = [[UIManagedDocument alloc] initWithFileURL:docURL]; |
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys: |
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, |
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; |
doc.persistentStoreOptions = options; |
if ([[NSFileManager defaultManager] fileExistsAtPath:[docURL path]]) { |
[doc openWithCompletionHandler:^(BOOL success){ |
if (!success) { |
// Handle the error. |
} |
}]; |
} |
else { |
[self addInitialData]; |
[doc saveToURL:docURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success){ |
if (!success) { |
// Handle the error. |
} |
}]; |
} |
Using a Managed Document’s Managed Object Context
To support asynchronous data writing, Core Data actually uses a pair of nested managed object contexts. The parent context is created on a private thread, the child context is created on the main thread. You get the child context from the managedObjectContext property. You should typically work with the child context, so must perform all operations using that context on the main thread. Where necessary, you can use performBlockAndWait: to ensure operations are performed correctly, as illustrated in the following example.
// This method might be implemented in a view controller that uses |
// a managed document's managed object context. |
-(void)addRecordFromBackgroundThread:(NSDictionary *)recordDictionary { |
NSDictionary *immutableDictionary = [recordDictionary copy]; |
NSManagedObjectContext *moc = self.managedObjectContext; |
[moc performBlockAndWait:^() { |
Record *newRecord = [NSEntityDescription insertNewObjectForEntityForName:@"Record" |
inManagedObjectContext:moc]; |
[newRecord updateFromDictionary:immutableDictionary]; |
}]; |
} |
The UIManagedDocument architecture leads to several considerations:
You should typically use the standard
UIDocumentmethods to save the document.If you save the child context directly, you only commit changes to the parent context and not to the document store. If you save the parent context directly, you sidestep other important operations that the document performs.
If appropriate, you can load data from a background thread directly to the parent context.
You can get the parent context using
parentContext. Loading data to the parent context means you do not perturb the child context’s operations. You can retrieve data loaded in the background simply by executing a fetch.You must not use the child context in
writeAdditionalContent:toURL:originalContentsURL:error:, or any of the asynchronousUIDocumentmethods.If you want to register for a managed object context’s change notifications (for example,
NSManagedObjectContextObjectsDidChangeNotification), you must make sure you register as an observer for the appropriate context (that is, not for all contexts).If you are using iCloud,
UIManagedDocumentdoes not support “additional content” in the document directory (seeadditionalContentForURL:error:and related methods).
Tasks
Managing the Core Data Stack
-
– configurePersistentStoreCoordinatorForURL:ofType:modelConfiguration:storeOptions:error: -
managedObjectContextproperty -
managedObjectModelproperty -
persistentStoreOptionsproperty -
modelConfigurationproperty -
– persistentStoreTypeForFileType:
Customizing Read and Write Operations
-
– readAdditionalContentFromURL:error: -
– additionalContentForURL:error: -
– writeAdditionalContent:toURL:originalContentsURL:error:
Naming the Persistent Store File
Properties
managedObjectContext
The document’s managed object context. (read-only)
Discussion
The document automatically creates a managed object context using its persistent store coordinator.
Availability
- Available in iOS 5.0 and later.
Declared In
UIManagedDocument.hmanagedObjectModel
The document’s managed object model. (read-only)
Discussion
Persistent documents always have a managed object model. The default model is the union of all models in the main bundle. You can specify a configuration to use with modelConfiguration. You can subclass UIManagedDocument to override this method if you need custom behavior.
Availability
- Available in iOS 5.0 and later.
Declared In
UIManagedDocument.hmodelConfiguration
A model configuration name to be passed when configuring the persistent store.
Discussion
By default, this value is nil.
Availability
- Available in iOS 5.0 and later.
See Also
Declared In
UIManagedDocument.hpersistentStoreOptions
Options used when creating the document’s persistent store.
Discussion
By default, this value is nil.
To support automatic migration, you might pass a dictionary like that shown in the following example.
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys: |
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, |
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; |
<#Managed document instance#>.persistentStoreOptions = options; |
Availability
- Available in iOS 5.0 and later.
See Also
Declared In
UIManagedDocument.hClass Methods
persistentStoreName
Returns the name for the persistent store file inside the document’s file package.
Return Value
The name for the persistent store file inside the document’s file package.
Discussion
This path component is appended to the document URL provided by UIDocument. The default name is persistentStore.
Availability
- Available in iOS 5.0 and later.
Declared In
UIManagedDocument.hInstance Methods
additionalContentForURL:error:
Handles writing non-Core Data content to the additional content directory in the document’s file package.
Parameters
- absoluteURL
The URL for the additional content directory in the document’s file package.
- error
Upon return, if a problem occurs, contains an error object that describes the problem.
Return Value
An object that contains the additional content for the document at absoluteURL, or nil if there is a problem.
Discussion
You override this method to perform to manage non-Core Data content to be stored in the additional content directory in the document’s file package.
If you implement this method, it is invoked automatically by contentsForType:error:. The returned object is passed to writeAdditionalContent:toURL:originalContentsURL:error:.
There is no need to invoke super’s implementation.
Special Considerations
A return value of nil indicates an error condition. To avoid generating an exception, you must return a value from this method. If it is not always the case that there will be additional content, you should return a sentinel value (for example, an NSNull instance) that you check for in writeAdditionalContent:toURL:originalContentsURL:error:.
The object returned from this method passed to writeAdditionalContent:toURL:originalContentsURL:error:. Because writeAdditionalContent:toURL:originalContentsURL:error: is executed on a different thread, you must ensure that the object you return is thread-safe. For example, you might return an NSData object containing an archive of the state you want to capture.
Additional content is not supported on iCloud.
Availability
- Available in iOS 5.0 and later.
See Also
Declared In
UIManagedDocument.hconfigurePersistentStoreCoordinatorForURL:ofType:modelConfiguration:storeOptions:error:
Creates or loads the document’s persistent store.
Parameters
- storeURL
The URL for the persistent store.
- fileType
The document’s file type.
- configuration
The managed object model configuration to use.
- storeOptions
The options used to configure the persistent store coordinator.
- error
Upon return, if a problem occurs, contains an error object that describes the problem.
Return Value
YES if configuration is successful, otherwise NO.
Discussion
You can override this method if you want customize the creation or loading of the document’s persistent store. For example, you can perform post-migration clean-up—if your application needs to migrate store data to use a new version of the managed object model, you can override this method to make additional modifications to the store after migration.
Availability
- Available in iOS 5.0 and later.
Declared In
UIManagedDocument.hpersistentStoreTypeForFileType:
Returns the Core Data store type for a given document file type.
Parameters
- fileType
The document file type.
Return Value
The persistent store type for fileType.
Discussion
Override this method to specify a persistent store type for a given document type.
The default returns NSSQLiteStoreType.
Availability
- Available in iOS 5.0 and later.
Declared In
UIManagedDocument.hreadAdditionalContentFromURL:error:
Handles reading non-Core Data content in the additional content directory in the document’s file package.
Parameters
- absoluteURL
The URL for the additional content directory in the document’s file package.
- error
Upon return, if a problem occurs, contains an error object that describes the problem.
Return Value
YES if the read operation is successful, otherwise NO.
Discussion
You override this method to read non-Core Data content from the additional content directory in the document’s file package.
If you implement this method, it is invoked automatically by readFromURL:error:.
There is no need to invoke super’s implementation.
Special Considerations
Additional content is not supported on iCloud.
Availability
- Available in iOS 5.0 and later.
Declared In
UIManagedDocument.hwriteAdditionalContent:toURL:originalContentsURL:error:
Handles writing non-Core Data content to the document’s file package.
Parameters
- content
An object that represents the additional content for the document.
This is the object returned from
additionalContentForURL:error:.- absoluteURL
The URL to which to write the additional content.
- absoluteOriginalContentsURL
The current URL of the document that is being saved.
- error
Upon return, if a problem occurs, contains an error object that describes the problem.
Return Value
YES if the write operation is successful, otherwise NO.
Discussion
You override this method to perform to write non-Core Data content in the additional content directory in the document’s file package. There are several issues to consider:
You should typically implement this method only if you have also implemented
additionalContentForURL:error:.Because this method is executed asynchronously, it is possible that the document’s state may be different from that at which the save operation was initiated. If you need to capture the document state at save time, you should do so in
additionalContentForURL:error:.If you implement this method, it is invoked automatically by
writeContents:andAttributes:safelyToURL:forSaveOperation:error:.There is no need to invoke
super’s implementation.
Special Considerations
Additional content is not supported on iCloud.
Availability
- Available in iOS 5.0 and later.
See Also
Declared In
UIManagedDocument.h© 2012 Apple Inc. All Rights Reserved. (Last updated: 2012-07-17)