Next Page > Hide TOC

NSManagedObjectContext Class Reference

Inherits from
Conforms to
Framework
/System/Library/Frameworks/CoreData.framework
Availability
Available in Mac OS X v10.4 and later.
Declared in
NSManagedObjectContext.h
Companion guides
Related sample code

Overview

An instance of NSManagedObjectContext represents a single “object space” or scratch pad in an application. Its primary responsibility is to manage a collection of managed objects. These objects form a group of related model objects that represent an internally consistent view of one or more persistent stores. A single managed object instance exists in one and only one context, but multiple copies of an object can exist in different contexts. Thus object uniquing is scoped to a particular context.

Life-cycle Management

The context is a powerful object with a central role in the life-cycle of managed objects, with responsibilities from life-cycle management (including faulting) to validation, inverse relationship handling, and undo/redo. Through a context you can retrieve or “fetch” objects from a persistent store, make changes to those objects, and then either discard the changes or—again through the context—commit them back to the persistent store. The context is responsible for watching for changes in its objects and maintains an undo manager so you can have finer-grained control over undo and redo. You can insert new objects and delete ones you have fetched, and commit these modifications to the persistent store.

If you are using Cocoa Bindings, the context can also serve as a controller. It implements the NSEditor and NSEditorRegistration informal protocols, although there should typically be little reason for you to directly invoke any method other than commitEditing or commitEditingWithDelegate:didCommitSelector:contextInfo:, and then only rarely.

Persistent Store Coordinator

A context always has a “parent” persistent store coordinator which provides the model and dispatches requests to the various persistent stores containing the data. Without a coordinator, a context is not fully functional. The context’s coordinator provides the managed object model and handles persistency. All objects fetched from an external store are registered in a context together with a global identifier (an instance of NSManagedObjectID) that’s used to uniquely identify each object to the external store.

Subclassing Notes

You are strongly discouraged from subclassing NSManagedObjectContext. The change tracking and undo management mechanisms are highly optimized and hence intricate and delicate. Interposing your own additional logic that might impact processPendingChanges can have unforeseen consequences. In situations such as store migration, Core Data will create instances of NSManagedObjectContext for its own use. Under these circumstances, you cannot rely on any features of your custom subclass. Any NSManagedObject subclass must always be fully compatible with NSManagedObjectContext (as opposed to any subclass of NSManagedObjectContext).

Tasks

Registering and Fetching Objects

Managed Object Management

Merging Changes from Another Context

Undo Management

Locking

Delete Propagation

Retaining Registered Objects

Managing the Persistent Store Coordinator

Managing the Staleness Interval

Managing the Merge Policy

Supporting NSKeyValueObserving Protocol

Supporting NSEditor and NSEditorRegistration Protocols

Instance Methods

assignObject:toPersistentStore:

Specifies the store in which a newly-inserted object will be saved.

- (void)assignObject:(id)object toPersistentStore:(NSPersistentStore *)store

Parameters
object

A managed object.

store

A persistent store.

Discussion

You can obtain a store from the persistent store coordinator, using for example persistentStoreForURL:.

Special Considerations

It is only necessary to use this method if the receiver’s persistent store coordinator manages multiple writable stores that have object’s entity in their configuration. Maintaining configurations in the managed object model can eliminate the need for invoking this method directly in many situations. If the receiver’s persistent store coordinator manages only a single writable store, or if only one store has object’s entity in its model, object will automatically be assigned to that store.

Availability
See Also
Related Sample Code
Declared In
NSManagedObjectContext.h

commitEditing

Returns a Boolean that indicates whether the receiver was able to commit any pending edits in known editors.

- (BOOL)commitEditing

Return Value

YES if the changes were successfully applied, otherwise NO.

Discussion

This method attempts to commit pending changes in known external editors—it does not commit unsaved changes to registered objects to their persistent store (contrast save:). Known editors are either instances of a subclass of NSController or (more rarely) user interface controls that may contain pending edits—such as text fields—that registered with the context using objectDidBeginEditing: and have not yet unregistered using a subsequent invocation of objectDidEndEditing:. Note that controllers only register with the context as being an editor if their content binding is not bound—if they have content of any kind, then they do not register.

The receiver iterates through the array of its known editors and invokes commitEditing on each until either it reaches the end of the array or an editor returns NO. If an editor returns NO, then the context also returns NO; otherwise the context returns YES.

You may find this method useful in some situations (typically if you are using Cocoa Bindings) when you want to ensure that pending changes are applied before a change in user interface state. For example, you may need to ensure that changes pending in a text field are applied before a window is closed. See also commitEditingWithDelegate:didCommitSelector:contextInfo: which performs a similar function but which allows you to specify a delegate that will handle any errors—the delegate is informed which editor failed to commit, which may be useful if you want to display an alert panel on the editor’s window.

See Also

commitEditingWithDelegate:didCommitSelector:contextInfo:

Attempts to commit any pending changes in known editors of the receiver.

-(void)commitEditingWithDelegate:(id)delegate didCommitSelector:(SEL)didCommitSelector contextInfo:(void *)contextInfo

Parameters
delegate

An object that can serve as the receiver's delegate. It should implement the method specified by didCommitSelector.

didCommitSelector

A selector that is invoked on delegate. The method specified by the selector must have the same signature as the following method:

- (void)editor:(id)editor didCommit:(BOOL)didCommit contextInfo:(void  *)contextInfo
contextInfo

Contextual information that is sent as the contextInfo argument to delegate when didCommitSelector is invoked.

Discussion

Provides support for the NSEditor informal protocol. This method attempts to commit pending changes in known external editors—it does not commit unsaved changes to registered objects to their persistent store (contrast save:). Known editors are either instances of a subclass of NSController or (more rarely) user interface controls that may contain pending edits—such as text fields—that registered with the context using objectDidBeginEditing: and have not yet unregistered using a subsequent invocation of objectDidEndEditing:. Note that controllers only register with the context as being an editor if their content binding is not bound—if they have content of any kind, then they do not register.

The receiver iterates through the array of its known editors and invokes commitEditing on each. The receiver then sends the message specified by the didCommitSelector selector to the specified delegate.

The didCommit argument is the value returned by the editor specified by editor from the commitEditing message. The contextInfo argument is the same value specified as the contextInfo parameter—you may use this value however you wish.

If an error occurs while attempting to commit, for example if key-value coding validation fails, your implementation of this method should typically send the view in which editing is being performed a presentError:modalForWindow:delegate:didRecoverSelector:contextInfo: message, specifying the view's containing window.

You may find this method useful in some situations (typically if you are using Cocoa Bindings) when you want to ensure that pending changes are applied before a change in user interface state. For example, you may need to ensure that changes pending in a text field are applied before a window is closed. See also commitEditing which performs a similar function but which allows you to handle any errors directly, although it provides no information beyond simple success/failure.

See Also

countForFetchRequest:error:

Returns the number of objects a given fetch request would have returned if it had been passed to executeFetchRequest:error:.

- (NSUInteger)countForFetchRequest:(NSFetchRequest *)request error:(NSError **)error

Parameters
request

A fetch request that specifies the search criteria for the fetch.

error

If there is a problem executing the fetch, upon return contains an instance of NSError that describes the problem.

Return Value

The number of objects a given fetch request would have returned if it had been passed to executeFetchRequest:error:. If an error occurrs during the processing of the request, returns NSNotFound.

Availability
Declared In
NSManagedObjectContext.h

deletedObjects

Returns the set of objects that will be removed from their persistent store during the next save operation.

- (NSSet *)deletedObjects

Return Value

The set of objects that will be removed from their persistent store during the next save operation.

Discussion

Note that the returned set does not necessarily include all the objects that have been deleted (using deleteObject:)—if an object has been inserted and deleted without an intervening save operation, it is not included in the set.

A managed object context does not post key-value observing notifications when the return value of deletedObjects changes—it does, however, post a NSManagedObjectContextObjectsDidChangeNotification notification when a change is made, and a NSManagedObjectContextDidSaveNotification notification when changes are committed (although again note that the set of deleted objects given for a NSManagedObjectContextDidSaveNotification does not include objects that were inserted and deleted without an intervening save operation—that is, they had not been saved to a persistent store).

Availability
See Also
Declared In
NSManagedObjectContext.h

deleteObject:

Specifies an object that should be removed from its persistent store when changes are committed.

- (void)deleteObject:(NSManagedObject *)object

Parameters
object

A managed object.

Discussion

When changes are committed, object will be removed from the uniquing tables. If object has not yet been saved to a persistent store, it is simply removed from the receiver.

Availability
See Also
Related Sample Code
Declared In
NSManagedObjectContext.h

detectConflictsForObject:

Marks an object for conflict detection.

- (void)detectConflictsForObject:(NSManagedObject *)object

Parameters
object

A managed object.

Discussion

If on the next invocation of save: object has been modified in its persistent store, the save fails. This allows optimistic locking for unchanged objects. Conflict detection is always performed on changed or deleted objects.

Availability
Declared In
NSManagedObjectContext.h

discardEditing

Causes the receiver to discard any changes in known editors, restoring the previous values

- (void)discardEditing

Discussion

Provides support for the NSEditor informal protocol. Causes the receiver to discard any changes in known editors, restoring the previous values. This method only applies to known editors (see commitEditing). To discard general edits, use rollback or reset.

See Also

executeFetchRequest:error:

Returns an array of objects that meet the criteria specified by a given fetch request.

- (NSArray *)executeFetchRequest:(NSFetchRequest *)request error:(NSError **)error

Parameters
request

A fetch request that specifies the search criteria for the fetch.

error

If there is a problem executing the fetch, upon return contains an instance of NSError that describes the problem.

Return Value

An array of objects that meet the criteria specified by request fetched from the receiver and from the persistent stores associated with the receiver’s persistent store coordinator. If an error occurs, returns nil. If no objects match the criteria specified by request, returns an empty array.

Discussion

Returned objects are registered with the receiver.

The following points are important to consider:

Objects that have been realized (populated, faults fired, “read from”, and so on) as well as pending updated, inserted, or deleted, are never changed by a fetch operation without developer intervention. If you fetch some objects, work with them, and then execute a new fetch that includes a superset of those objects, you do not get new instances or update data for the existing objects—you get the existing objects with their current in-memory state.

Availability
Related Sample Code
Declared In
NSManagedObjectContext.h

hasChanges

Returns a Boolean value that indicates whether the receiver has uncommitted changes.

- (BOOL)hasChanges

Return Value

YES if the receiver has uncommitted changes, otherwise NO.

Discussion

This property is not key-value observing compliant (see Key-Value Observing Programming Guide)—if you are using Cocoa bindings, you cannot bind to the hasChanges property of a managed object context.

Availability
See Also
Declared In
NSManagedObjectContext.h

insertedObjects

Returns the set of objects that have been inserted into the receiver but not yet saved in a persistent store.

- (NSSet *)insertedObjects

Return Value

The set of objects that have been inserted into the receiver but not yet saved in a persistent store.

Discussion

A managed object context does not post key-value observing notifications when the return value of insertedObjects changes—it does, however, post a NSManagedObjectContextObjectsDidChangeNotification notification when a change is made, and a NSManagedObjectContextDidSaveNotification notification when changes are committed.

Availability
See Also
Declared In
NSManagedObjectContext.h

insertObject:

Registers an object to be inserted in the receiver’s persistent store the next time changes are saved.

- (void)insertObject:(NSManagedObject *)object

Parameters
object

A managed object.

Discussion

The managed object (object) is registered in the receiver with a temporary global ID. It is assigned a permanent global ID when changes are committed. If the current transaction is rolled back (for example, if the receiver is sent a rollback message) before a save operation, the object is unregistered from the receiver.

Availability
See Also
Declared In
NSManagedObjectContext.h

lock

Attempts to acquire a lock on the receiver.

- (void)lock

Discussion

This method blocks a thread’s execution until the lock can be acquired. An application protects a critical section of code by requiring a thread to acquire a lock before executing the code. Once the critical section is past, the thread relinquishes the lock by invoking unlock.

Sending this message to a managed object context helps the framework to understand the scope of a transaction in a multi-threaded environment. It is preferable to use the NSManagedObjectContext’s implementation of NSLocking instead using of a separate mutex object.

If you lock (or successfully tryLock) a managed object context, the thread in which the lock call is made must have a retain until it invokes unlock. If you do not properly retain a context in a multi-threaded environment, this will result in deadlock.

Availability
See Also
Declared In
NSManagedObjectContext.h

mergeChangesFromContextDidSaveNotification:

Merges the changes specified in a given notification.

- (void)mergeChangesFromContextDidSaveNotification:(NSNotification *)notification

Parameters
notification

An instance of an NSManagedObjectContextDidSaveNotification notification posted by another context.

Discussion

This method refreshes any objects which have been updated in the other context, faults in any newly-inserted objects, and invokes deleteObject:: on those which have been deleted.

You can use this method to, for example, update a managed object context on the main thread with work completed in another context in another thread. You must, though, lock the receiver or otherwise ensure thread safety (that is, the notification contents are handled safely by Core Data, but the receiver's usage is still expected to conform to the standard Core Data threading policies). For example, you might implement a method to handle a notification that a worker thread had finished saving as follows:

- (void)workerThreadObjectContextDidSave:(NSNotification*)saveNotification {
    NSManagedObjectContext *appMOC = [[NSApp delegate] managedObjectContext];
    [appMOC performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:)
                             withObject:saveNotification
                          waitUntilDone:NO];
}

In this case, serialization is enforced by the main thread's run loop.

Availability
Declared In
NSManagedObjectContext.h

mergePolicy

Returns the merge policy of the receiver.

- (id)mergePolicy

Return Value

The receiver’s merge policy.

Discussion

The default is NSErrorMergePolicy.

Availability
Declared In
NSManagedObjectContext.h

objectDidBeginEditing:

Provides support for the NSEditorRegistration informal protocol.

- (void)objectDidBeginEditing:(id)editor

Parameters
editor

An external editor that has changes that may affect the receiver.

Discussion

This message should be sent to the receiver when editor has uncommitted changes that can affect the receiver. There should typically be no reason for you to invoke this method directly.

See Also

objectDidEndEditing:

Provides support for theNSEditorRegistration informal protocol.

- (void)objectDidEndEditing:(id)editor

Parameters
editor

An external editor that has made changes that affect the receiver.

Discussion

This message should be sent to the receiver when editor has finished editing a property belonging to the receiver. There should typically be no reason for you to invoke this method directly.

See Also

objectRegisteredForID:

Returns the object for a specified ID, if the object is registered with the receiver.

- (NSManagedObject *)objectRegisteredForID:(NSManagedObjectID *)objectID

Parameters
objectID

An object ID.

Return Value

The object for the specified ID if it is registered with the receiver, otherwise nil.

Availability
See Also
Related Sample Code
Declared In
NSManagedObjectContext.h

objectWithID:

Returns the object for a specified ID.

- (NSManagedObject *)objectWithID:(NSManagedObjectID *)objectID

Parameters
objectID

An object ID.

Return Value

The object for the specified ID.

Discussion

If the object is not registered in the context, it may be fetched or returned as a fault. This method always returns an object. The data in the persistent store represented by objectID is assumed to exist—if it does not, the returned object throws an exception when you access any property (that is, when the fault is fired). The benefit of this behavior is that it allows you to create and use faults, then create the underlying rows later or in a separate context.

Availability
See Also
Related Sample Code
Declared In
NSManagedObjectContext.h

observeValueForKeyPath:ofObject:change:context:

This message is sent to the receiver when the value at the specified key path relative to the given object has changed.

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

Parameters
keyPath

The key path, relative to object, to the value that has changed.

object

The source object of the key path keyPath.

change

A dictionary that describes the changes that have been made to the value of the property at the key path keyPath relative to object. For possible values, see NSKeyValueObserving.

context

The value that was provided when the receiver was registered to receive key-value observation notifications.

Availability
Declared In
NSManagedObjectContext.h

obtainPermanentIDsForObjects:error:

Converts to permanent IDs the object IDs of the objects in a given array.

- (BOOL)obtainPermanentIDsForObjects:(NSArray *)objects error:(NSError **)error

Parameters
objects

An array of managed objects.

error

If an error occurs, upon return contains an NSError object that describes the problem.

Return Value

YES if permanent IDs are obtained for all the objects in objects, otherwise NO.

Discussion

This method converts the object ID of each managed object in objects to a permanent ID. Although the object will have a permanent ID, it will still respond positively to isInserted until it is saved. Any object that already has a permanent ID is ignored.

Any object not already assigned to a store is assigned based on the same rules Core Data uses for assignment during a save operation (first writable store supporting the entity, and appropriate for the instance and its related items).

Special Considerations

This method results in a transaction with the underlying store which changes the file’s modification date.

This results an additional consideration if you invoke this method on the managed object context associated with an instance of NSPersistentDocument. Instances of NSDocument need to know that they are in sync with the underlying content. To avoid problems, after invoking this method you must therefore update the document’s modification date (using setFileModificationDate:).

Availability
Declared In
NSManagedObjectContext.h

persistentStoreCoordinator

Returns the persistent store coordinator of the receiver.

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator

Return Value

The persistent store coordinator of the receiver.

Availability
Related Sample Code
Declared In
NSManagedObjectContext.h

processPendingChanges

Forces the receiver to process changes to the object graph.

- (void)processPendingChanges

Discussion

This method causes changes to registered managed objects to be recorded with the undo manager.

In AppKit-based applications, this method is invoked automatically at least once during the event loop (at the end of the loop)—it may be called more often than that if the framework needs to coalesce your changes before doing something else. You can also invoke it manually to coalesce any pending unprocessed changes.

Availability
See Also
Related Sample Code
Declared In
NSManagedObjectContext.h

propagatesDeletesAtEndOfEvent

Returns a Boolean that indicates whether the receiver propagates deletes at the end of the event in which a change was made.

- (BOOL)propagatesDeletesAtEndOfEvent

Return Value

YES if the receiver propagates deletes at the end of the event in which a change was made, NO if it propagates deletes only immediately before saving changes.

Availability
See Also
Declared In
NSManagedObjectContext.h

redo

Sends an redo message to the receiver’s undo manager, asking it to reverse the latest undo operation applied to objects in the object graph.

- (void)redo

Availability
See Also
Declared In
NSManagedObjectContext.h

refreshObject:mergeChanges:

Updates the persistent properties of a managed object to use the latest values from the persistent store.

- (void)refreshObject:(NSManagedObject *)object mergeChanges:(BOOL)flag

Parameters
object

A managed object.

flag

A Boolean value.

If flag is NO, then object is turned into a fault and any pending changes are lost. The object remains a fault until it is accessed again, at which time its property values will be reloaded from the store or last cached state.

If flag is YES, then object’s property values are reloaded from the values from the store or the last cached state then any changes that were made (in the local context) are re-applied over those (now newly updated) values. (If flag is YES the merge of the values into object will always succeed—in this case there is therefore no such thing as a “merge conflict” or a merge that is not possible.)

Discussion

If the staleness interval (see stalenessInterval) has not been exceeded, any available cached data is reused instead of executing a new fetch. If flag is YES, this method does not affect any transient properties; if flag is NO, transient properties are released.

You typically use this method to ensure data freshness if more than one managed object context may use the same persistent store simultaneously, in particular if you get an optimistic locking failure when attempting to save.

It is important to note that turning object into a fault (flag is NO) also causes related managed objects (that is, those to which object has a reference) to be released, so you can also use this method to trim a portion of your object graph you want to constrain memory usage.

Availability
See Also
Related Sample Code
Declared In
NSManagedObjectContext.h

registeredObjects

Returns the set of objects registered with the receiver.

- (NSSet *)registeredObjects

Return Value

The set of objects registered with the receiver.

Discussion

A managed object context does not post key-value observing notifications when the return value of registeredObjects changes.

Availability
See Also
Declared In
NSManagedObjectContext.h

reset

Returns the receiver to its base state.

- (void)reset

Discussion

All the receiver's managed objects are “forgotten.” If you use this method, you should ensure that you also discard references to any managed objects fetched using the receiver, since they will be invalid afterwards.

Availability
See Also
Related Sample Code
Declared In
NSManagedObjectContext.h

retainsRegisteredObjects

Returns a Boolean that indicates whether the receiver sends a retain message to objects upon registration.

- (BOOL)retainsRegisteredObjects

Return Value

YES if the receiver sends a retain message to objects upon registration, otherwise NO.

Availability
See Also
Declared In
NSManagedObjectContext.h

rollback

Removes everything from the undo stack, discards all insertions and deletions, and restores updated objects to their last committed values.

- (void)rollback

Discussion

This method does not refetch data from the persistent store or stores.

Availability
See Also
Declared In
NSManagedObjectContext.h

save:

Attempts to commit unsaved changes to registered objects to their persistent store.

- (BOOL)save:(NSError **)error

Parameters
error

A pointer to an NSError object. You do not need to create an NSError object. The save operation aborts after the first failure if you pass NULL.

Return Value

YES if the save succeeds, otherwise NO.

Discussion

If there were multiple errors (for example several edited objects had validation failures) the description of NSError returned indicates that there were multiple errors, and its userInfo dictionary contains the key NSDetailedErrors. The value associated with the NSDetailedErrors key is an array that contains the individual NSError objects.

Availability
See Also
Related Sample Code
Declared In
NSManagedObjectContext.h

setMergePolicy:

Sets the merge policy of the receiver.

- (void)setMergePolicy:(id)mergePolicy

Parameters
mergePolicy

The merge policy of the receiver. For possible values, see “Merge Policies”.

Availability
Declared In
NSManagedObjectContext.h

setPersistentStoreCoordinator:

Sets the persistent store coordinator of the receiver.

- (void)setPersistentStoreCoordinator:(NSPersistentStoreCoordinator *)coordinator

Parameters
coordinator

The persistent store coordinator of the receiver.

Discussion

The coordinator provides the managed object model and handles persistency. Note that multiple contexts can share a coordinator.

This method raises an exception if coordinator is nil. If you want to “disconnect" a context from its persistent store coordinator, you should simply release all references to the context and allow it to be deallocated normally.

Availability
Related Sample Code
Declared In
NSManagedObjectContext.h

setPropagatesDeletesAtEndOfEvent:

Sets whether the context propagates deletes to related objects at the end of the event.

- (void)setPropagatesDeletesAtEndOfEvent:(BOOL)flag

Parameters
Flag

A Boolean value that indicates whether the context propagates deletes to related objects at the end of the event (YES) or not (NO).

Discussion

The default is YES. If the value is NO, then deletes are propagated during a save operation.

Availability
See Also
Declared In
NSManagedObjectContext.h

setRetainsRegisteredObjects:

Sets whether or not the receiver retains all registered objects, or only objects necessary for a pending save (those that are inserted, updated, deleted, or locked).

- (void)setRetainsRegisteredObjects:(BOOL)flag

Parameters
flag

A Boolean value.

If flag is NO, then registered objects are retained only when they are inserted, updated, deleted, or locked.

If flag is YES, then all registered objects are retained.

Discussion

The default is NO.

Availability
See Also
Declared In
NSManagedObjectContext.h

setStalenessInterval:

Sets the staleness interval of the receiver.

- (void)setStalenessInterval:(NSTimeInterval)expiration

Parameters
expiration

The staleness interval of the receiver.

Discussion

The staleness interval controls whether fulfilling a fault uses data previously fetched by the application, or issues a new fetch (see also refreshObject:mergeChanges:). The staleness interval does not affect objects currently in use (that is, it is not used to automatically update property values from a persistent store after a certain period of time).

The expiration value is applied on a per object basis. It is the relative time until cached data (snapshots) should be considered stale. For example, a value of 300.0 informs the context to utilize cached information for no more than 5 minutes after an object was originally fetched.

The default is infinite staleness (represented by an interval of 0).

Note that the staleness interval is a hint and may not be supported by all persistent store types. It is not used by XML and binary stores, since these stores maintain all current values in memory.

Availability
See Also
Declared In
NSManagedObjectContext.h

setUndoManager:

Sets the undo manager of the receiver.

- (void)setUndoManager:(NSUndoManager *)undoManager

Parameters
undoManager

The undo manager of the receiver.

Discussion

By default, a context provides its own undo manager. You can set the undo manager to nil to disable undo support, for example in a large import process. For more details, see Core Data Programming Guide.

Availability
See Also
Declared In
NSManagedObjectContext.h

stalenessInterval

Returns the staleness interval of the receiver.

- (NSTimeInterval)stalenessInterval

Return Value

The staleness interval of the receiver.

Discussion

For more details, see setStalenessInterval:.

Availability
See Also
Declared In
NSManagedObjectContext.h

tryLock

Attempts to acquire a lock.

- (BOOL)tryLock

Return Value

YES if a lock was acquired, NO otherwise.

Discussion

This method returns immediately after the attempt to acquire a lock.

Availability
See Also
Declared In
NSManagedObjectContext.h

undo

Sends an undo message to the receiver’s undo manager, asking it to reverse the latest uncommitted changes applied to objects in the object graph.

- (void)undo

Availability
See Also
Declared In
NSManagedObjectContext.h

undoManager

Returns the undo manager of the receiver.

- (NSUndoManager *)undoManager

Return Value

The undo manager of the receiver.

Discussion

By default, a context provides its own undo manager. For more details, see setUndoManager:.

Availability
See Also
Related Sample Code
Declared In
NSManagedObjectContext.h

unlock

Relinquishes a previously acquired lock.

- (void)unlock

Availability
See Also
Declared In
NSManagedObjectContext.h

updatedObjects

Returns the set of objects registered with the receiver that have uncommitted changes.

- (NSSet *)updatedObjects

Return Value

The set of objects registered with the receiver that have uncommitted changes.

Discussion

A managed object context does not post key-value observing notifications when the return value of updatedObjects changes—it does, however, post a NSManagedObjectContextObjectsDidChangeNotification notification when a change is made, and a NSManagedObjectContextDidSaveNotification notification when changes are committed.

Availability
See Also
Declared In
NSManagedObjectContext.h

Constants

NSManagedObjectContext Change Notification User Info Keys

Core Data uses these string constants as keys in the user info dictionary in managed object context notifications (NSManagedObjectContextObjectsDidChangeNotification and NSManagedObjectContextDidSaveNotification).

NSString * const NSInsertedObjectsKey;
NSString * const NSUpdatedObjectsKey;
NSString * const NSDeletedObjectsKey;
NSString * const NSRefreshedObjectsKey;
NSString * const NSInvalidatedObjectsKey;
NSString * const NSInvalidatedAllObjectsKey;

Constants
NSInsertedObjectsKey

Key for the set of objects that were inserted into the context.

Available in Mac OS X v10.4 and later.

Declared in NSManagedObjectContext.h.

NSUpdatedObjectsKey

Key for the set of objects that were updated.

Available in Mac OS X v10.4 and later.

Declared in NSManagedObjectContext.h.

NSDeletedObjectsKey

Key for the set of objects that were marked for deletion during the previous event.

Note that the set of deleted objects given for a NSManagedObjectContextDidSaveNotification does not include objects that were inserted and deleted without an intervening save operation—that is, they had not been saved to a persistent store. See also deletedObjects (NSManagedObjectContext) and isDeleted (NSManagedObject).

Available in Mac OS X v10.4 and later.

Declared in NSManagedObjectContext.h.

NSRefreshedObjectsKey

Key for the set of objects that were refreshed.

Available in Mac OS X v10.5 and later.

Declared in NSManagedObjectContext.h.

NSInvalidatedObjectsKey

Key for the set of objects that were invalidated.

Available in Mac OS X v10.5 and later.

Declared in NSManagedObjectContext.h.

NSInvalidatedAllObjectsKey

Key that specifies that all objects in the context have been invalidated.

Available in Mac OS X v10.5 and later.

Declared in NSManagedObjectContext.h.

Declared In
NSManagedObjectContext.h

Merge Policies

Merge policy constants define the way conflicts are handled during a save operation.

id NSErrorMergePolicy;
id NSMergeByPropertyStoreTrumpMergePolicy;
id NSMergeByPropertyObjectTrumpMergePolicy;
id NSOverwriteMergePolicy;
id NSRollbackMergePolicy;

Constants
NSErrorMergePolicy

This policy causes a save to fail if there are any merge conflicts.

In the case of failure, the save method returns with an error with a userInfo dictionary that contains the key @"conflictList"; the corresponding value is an array of conflict records.

Available in Mac OS X v10.4 and later.

Declared in NSManagedObjectContext.h.

NSMergeByPropertyStoreTrumpMergePolicy

This policy merges conflicts between the persistent store’s version of the object and the current in-memory version, giving priority to external changes.

The merge occurs by individual property. For properties that have been changed in both the external source and in memory, the external changes trump the in-memory ones.

Available in Mac OS X v10.4 and later.

Declared in NSManagedObjectContext.h.

NSMergeByPropertyObjectTrumpMergePolicy

This policy merges conflicts between the persistent store’s version of the object and the current in-memory version, giving priority to in-memory changes.

The merge occurs by individual property. For properties that have been changed in both the external source and in memory, the in-memory changes trump the external ones.

Available in Mac OS X v10.4 and later.

Declared in NSManagedObjectContext.h.

NSOverwriteMergePolicy

This policy overwrites state in the persistent store for the changed objects in conflict.

Changed objects’ current state is forced upon the persistent store.

Available in Mac OS X v10.4 and later.

Declared in NSManagedObjectContext.h.

NSRollbackMergePolicy

This policy discards in-memory state changes for objects in conflict.

The persistent store’s version of the objects’ state is used.

Available in Mac OS X v10.4 and later.

Declared in NSManagedObjectContext.h.

Discussion

The default policy is the NSErrorMergePolicy. It is the only policy that requires action to correct any conflicts; the other policies make a save go through silently by making changes following their rules.

Declared In
NSManagedObjectContext.h

The following constants, defined in CoreDataErrors.h, relate to errors returned following validation failures or problems encountered during a save operation.

NSValidationObjectErrorKeyKey for the object that failed to validate for a validation error.
NSAffectedStoresErrorKeyThe key for stores prompting an error.
NSAffectedObjectsErrorKeyThe key for objects prompting an error.

Each conflict record in the @"conflictList" array in the userInfo dictionary for an error from the NSErrorMergePolicy is a dictionary containing some of the keys described in the following table. Of the cachedRow, databaseRow, and snapshot keys, only two will be present depending on whether the conflict is between the managed object context and the persistent store coordinator (snapshot and cachedRow) or between the persistent store coordinator and the persistent store (cachedRow and databaseRow).

Constant

Description

@"object"

The managed object that could not be saved.

@"snapshot"

A dictionary of key-value pairs for the properties that represents the managed object context’s last saved state for this managed object.

@"cachedRow"

A dictionary of key-value pairs for the properties that represents the persistent store's last saved state for this managed object.

@"databaseRow"

A dictionary of key-value pairs for the properties that represents the database's current state for this managed object.

@"newVersion"

An NSNumber object whose value is latest version number of this managed object.

@"oldVersion"

As NSNumber object whose value is the version number that this managed object context last saved for this managed object.

Notifications

NSManagedObjectContextObjectsDidChangeNotification

Posted when values of properties of objects contained in a managed object context are changed.

The notification is posted during processPendingChanges, after the changes have been processed, but before it is safe to call save: again (if you try, you will generate an infinite loop).

The notification object is the managed object context. The userInfo dictionary contains the following keys: NSInsertedObjectsKey, NSUpdatedObjectsKey, and NSDeletedObjectsKey.

Note that this notification is posted only when managed objects are changed; it is not posted when managed objects are added to a context as the result of a fetch.

Availability
Declared In
NSManagedObjectContext.h

NSManagedObjectContextDidSaveNotification

Posted whenever a managed object context completes a save operation.

The notification object is the managed object context. The userInfo dictionary contains the following keys: NSInsertedObjectsKey, NSUpdatedObjectsKey, and NSDeletedObjectsKey.

Availability
Declared In
NSManagedObjectContext.h

Next Page > Hide TOC


© 2008 Apple Inc. All Rights Reserved. (Last updated: 2008-10-15)


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.