iOS Developer Library

Developer

CoreData Framework Reference NSManagedObjectContext Class Reference

Options
Deployment Target:

On This Page
Language:

NSManagedObjectContext

Inherits From


Conforms To


Import Statement


Swift

import CoreData

Objective-C

@import CoreData;

Availability


Available in iOS 3.0 and later

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.

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.

Parent Store

Managed object contexts have a parent store from which they retrieve data representing managed objects and through which they commit changes to managed objects.

Prior to OS X v10.7 and iOS v5.0, the parent store is always a persistent store coordinator. In OS X v10.7 and later and iOS v5.0 and later, the parent store may be another managed object context. Ultimately the root of a context’s ancestry must be a persistent store coordinator. The coordinator provides the managed object model and dispatches requests to the various persistent stores containing the data.

If a context’s parent store is another managed object context, fetch and save operations are mediated by the parent context instead of a coordinator. This pattern has a number of usage scenarios, including:

  • Performing background operations on a second thread or queue.

  • Managing discardable edits, such as in an inspector window or view.

As the first scenario implies, a parent context can service requests from children on different threads. You cannot, therefore, use parent contexts created with the thread confinement type (see Concurrency).

When you save changes in a context, the changes are only committed “one store up.” If you save a child context, changes are pushed to its parent. Changes are not saved to the persistent store until the root context is saved. (A root managed object context is one whose parent context is nil.) In addition, a parent does not pull changes from children before it saves. You must save a child context if you want ultimately to commit the changes.

Notifications

A context posts notifications at various points—see NSManagedObjectContextObjectsDidChangeNotification for example. Typically, you should register to receive these notifications only from known contexts:

  • [[NSNotificationCenter defaultCenter] addObserver:self
  • selector:@selector(<#Selector name#>)
  • name:NSManagedObjectContextDidSaveNotification
  • object:<#A managed object context#>];

Several system frameworks use Core Data internally. If you register to receive these notifications from all contexts (by passing nil as the object parameter to a method such as addObserver:selector:name:object:), then you may receive unexpected notifications that are difficult to handle.

Concurrency

Core Data uses thread (or serialized queue) confinement to protect managed objects and managed object contexts (see Concurrency with Core Data). A consequence of this is that a context assumes the default owner is the thread or queue that allocated it—this is determined by the thread that calls its init method. You should not, therefore, initialize a context on one thread then pass it to a different thread. Instead, you should pass a reference to a persistent store coordinator and have the receiving thread/queue create a new context derived from that. If you use NSOperation, you must create the context in main (for a serial queue) or start (for a concurrent queue).

In OS X v10.7 and later and iOS v5.0 and later, when you create a context you can specify the concurrency pattern with which you will use it using initWithConcurrencyType:. When you create a managed object context using initWithConcurrencyType:, you have three options for its thread (queue) association

  • Confinement (NSConfinementConcurrencyType)

    For backwards compatibility, this is the default. You promise that context will not be used by any thread other than the one on which you created it. In general, to make the behavior explicit you’re encouraged to use one of the other types instead.

    You can only use this concurrency type if the managed object context’s parent store is a persistent store coordinator.

  • Private queue (NSPrivateQueueConcurrencyType)

    The context creates and manages a private queue.

  • Main queue (NSMainQueueConcurrencyType)

    The context is associated with the main queue, and as such is tied into the application’s event loop, but it is otherwise similar to a private queue-based context. You use this queue type for contexts linked to controllers and UI objects that are required to be used only on the main thread.

If you use contexts using the confinement pattern, you send the contexts messages directly; it’s up to you to ensure that you send the messages from the right queue.

You use contexts using the queue-based concurrency types in conjunction with performBlock: and performBlockAndWait:. You group “standard” messages to send to the context within a block to pass to one of these methods. There are two exceptions:

  • Setter methods on queue-based managed object contexts are thread-safe. You can invoke these methods directly on any thread.

  • If your code is executing on the main thread, you can invoke methods on the main queue style contexts directly instead of using the block based API.

performBlock: and performBlockAndWait: ensure the block operations are executed on the queue specified for the context. The performBlock: method returns immediately and the context executes the block methods on its own thread. With the performBlockAndWait: method, the context still executes the block methods on its own thread, but the method doesn’t return until the block is executed.

It’s important to appreciate that blocks are executed as a distinct body of work. As soon as your block ends, anyone else can enqueue another block, undo changes, reset the context, and so on. Thus blocks may be quite large, and typically end by invoking save:.

  • __block NSError *error;
  • __block BOOL savedOK = NO;
  • [myMOC performBlockAndWait:^{
  • // Do lots of things with the context.
  • savedOK = [myMOC save:&error];
  • }];

You can also perform other operations, such as:

  • NSFetchRequest *fr = [NSFetchRequest fetchRequestWithEntityName:@"Entity"];
  • __block NSUInteger rCount = 0;
  • [context performBlockAndWait:^() {
  • NSError *error;
  • rCount = [context countForFetchRequest:fr error:&error];
  • if (rCount == NSNotFound) {
  • // Handle the error.
  • } }];
  • NSLog(@"Retrieved %d items", (int)rCount);

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 (that is, it cannot rely on features of a subclass of NSManagedObjectContext).

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

    Declaration

    Swift

    func executeFetchRequest(_ request: NSFetchRequest, error error: NSErrorPointer) -> [AnyObject]?

    Objective-C

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

    • If the fetch request has no predicate, then all instances of the specified entity are retrieved, modulo other criteria below.

    • An object that meets the criteria specified by request (it is an instance of the entity specified by the request, and it matches the request’s predicate if there is one) and that has been inserted into a context but which is not yet saved to a persistent store, is retrieved if the fetch request is executed on that context.

    • If an object in a context has been modified, a predicate is evaluated against its modified state, not against the current state in the persistent store. Therefore, if an object in a context has been modified such that it meets the fetch request’s criteria, the request retrieves it even if changes have not been saved to the store and the values in the store are such that it does not meet the criteria. Conversely, if an object in a context has been modified such that it does not match the fetch request, the fetch request will not retrieve it even if the version in the store does match.

    • If an object has been deleted from the context, the fetch request does not retrieve it even if that deletion has not been saved to a store.

    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.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

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

    Declaration

    Swift

    func countForFetchRequest(_ request: NSFetchRequest, error error: NSErrorPointer) -> Int

    Objective-C

    - (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:, or NSNotFound if an error occurs.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

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

    Declaration

    Swift

    func objectRegisteredForID(_ objectID: NSManagedObjectID) -> NSManagedObject?

    Objective-C

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

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

  • Returns the object for a specified ID.

    Declaration

    Swift

    func objectWithID(_ objectID: NSManagedObjectID) -> NSManagedObject

    Objective-C

    - (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 data later or in a separate context.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

  • Returns the object for the specified ID.

    Declaration

    Swift

    func existingObjectWithID(_ objectID: NSManagedObjectID, error error: NSErrorPointer) -> NSManagedObject?

    Objective-C

    - (NSManagedObject *)existingObjectWithID:(NSManagedObjectID *)objectID error:(NSError **)error

    Parameters

    objectID

    The object ID for the requested object.

    error

    If there is a problem in retrieving the object specified by objectID, upon return contains an error that describes the problem.

    Return Value

    The object specified by objectID. If the object cannot be fetched, or does not exist, or cannot be faulted, it returns nil.

    Discussion

    If there is a managed object with the given ID already registered in the context, that object is returned directly; otherwise the corresponding object is faulted into the context.

    This method might perform I/O if the data is uncached.

    Unlike objectWithID:, this method never returns a fault.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

  • The set of objects registered with the receiver. (read-only)

    Declaration

    Swift

    var registeredObjects: Set<NSObject> { get }

    Objective-C

    @property(nonatomic, readonly, strong) NSSet *registeredObjects

    Discussion

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

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

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

    Declaration

    Swift

    func insertObject(_ object: NSManagedObject)

    Objective-C

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

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

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

    Declaration

    Swift

    func deleteObject(_ object: NSManagedObject)

    Objective-C

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

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

    See Also

    – deletedObjects
    isDeleted (NSManagedObject)

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

    Declaration

    Swift

    func assignObject(_ object: AnyObject, toPersistentStore store: NSPersistentStore)

    Objective-C

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

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

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

    Declaration

    Swift

    func obtainPermanentIDsForObjects(_ objects: [AnyObject], error error: NSErrorPointer) -> Bool

    Objective-C

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

    YEStrue if permanent IDs are obtained for all the objects in objects, otherwise NOfalse.

    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.

    In OS X, 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:).

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

  • Marks an object for conflict detection.

    Declaration

    Swift

    func detectConflictsForObject(_ object: NSManagedObject)

    Objective-C

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

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

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

    Declaration

    Swift

    func refreshObject(_ object: NSManagedObject, mergeChanges flag: Bool)

    Objective-C

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

    Parameters

    object

    A managed object.

    flag

    A Boolean value.

    If flag is NOfalse, 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 YEStrue, 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 YEStrue 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 YEStrue, this method does not affect any transient properties; if flag is NOfalse, transient properties are disposed of.

    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.

    Turning object into a fault (flag is NOfalse) means that strong references to related managed objects (that is, those to which object has a reference) are broken, so you can also use this method to trim a portion of your object graph you want to constrain memory usage.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

  • Forces the receiver to process changes to the object graph.

    Declaration

    Swift

    func processPendingChanges()

    Objective-C

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

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

  • The set of objects that have been inserted into the receiver but not yet saved in a persistent store. (read-only)

    Declaration

    Swift

    var insertedObjects: Set<NSObject> { get }

    Objective-C

    @property(nonatomic, readonly, strong) NSSet *insertedObjects

    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 NSManagedObjectContextWillSaveNotification and a NSManagedObjectContextDidSaveNotification notification before and after changes are committed respectively.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

  • The set of objects registered with the receiver that have uncommitted changes. (read-only)

    Declaration

    Swift

    var updatedObjects: Set<NSObject> { get }

    Objective-C

    @property(nonatomic, readonly, strong) NSSet *updatedObjects

    Discussion

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

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

  • The set of objects that will be removed from their persistent store during the next save operation. (read-only)

    Declaration

    Swift

    var deletedObjects: Set<NSObject> { get }

    Objective-C

    @property(nonatomic, readonly, strong) NSSet *deletedObjects

    Discussion

    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. A context does, however, post a NSManagedObjectContextObjectsDidChangeNotification notification when a change is made, and a NSManagedObjectContextWillSaveNotification notification and a NSManagedObjectContextDidSaveNotification notification before and after changes are committed respectively (although again the set of deleted objects given for an NSManagedObjectContextDidSaveNotification does not include objects that were inserted and deleted without an intervening save operation—that is, they had never been saved to a persistent store).

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

  • Initializes a context with a given concurrency type.

    Declaration

    Swift

    init(concurrencyType type: NSManagedObjectContextConcurrencyType)

    Objective-C

    - (instancetype)initWithConcurrencyType:(NSManagedObjectContextConcurrencyType)type

    Parameters

    type

    The concurrency pattern with which context will be used.

    Return Value

    A context initialized to use the given concurrency type.

    Discussion

    For more details on use of this method, see Concurrency.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 5.0 and later

  • The concurrency type for the receiver. (read-only)

    Declaration

    Swift

    var concurrencyType: NSManagedObjectContextConcurrencyType { get }

    Objective-C

    @property(readonly) NSManagedObjectContextConcurrencyType concurrencyType

    Discussion

    For more details on concurrency type, see Concurrency.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 5.0 and later

  • Merges the changes specified in a given notification.

    Declaration

    Swift

    func mergeChangesFromContextDidSaveNotification(_ notification: NSNotification)

    Objective-C

    - (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 pass a NSManagedObjectContextDidSaveNotification notification posted by a managed object context on another thread, however you must not use the managed objects in the user info dictionary directly. For more details, see Concurrency with Core Data.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

  • The undo manager of the receiver.

    Declaration

    Swift

    var undoManager: NSUndoManager?

    Objective-C

    @property(nonatomic, strong) NSUndoManager *undoManager

    Discussion

    You can set the undo manager to nil to disable undo support. This provides a performance benefit if you do not want to support undo for a particular context, for example in a large import process—see Core Data Programming Guide.

    If a context does not have an undo manager, you can enable undo support by setting one. You may also replace a context’s undo manager if you want to integrate the context’s undo operations with another undo manager in your application.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

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

    Declaration

    Swift

    func undo()

    Objective-C

    - (void)undo

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

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

    Declaration

    Swift

    func redo()

    Objective-C

    - (void)redo

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

  • Returns the receiver to its base state.

    Declaration

    Swift

    func reset()

    Objective-C

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

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

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

    Declaration

    Swift

    func rollback()

    Objective-C

    - (void)rollback

    Discussion

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

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

  • Attempts to commit unsaved changes to registered objects to the receiver’s parent store.

    Declaration

    Swift

    func save(_ error: NSErrorPointer) -> Bool

    Objective-C

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

    YEStrue if the save succeeds, otherwise NOfalse.

    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.

    If a context’s parent store is a persistent store coordinator, then changes are committed to the external store. If a context’s parent store is another managed object context, then save: only updates managed objects in that parent store. To commit changes to the external store, you must save changes in the chain of contexts up to and including the context whose parent is the persistent store coordinator.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

  • A Boolean value that indicates whether the receiver has uncommitted changes. (read-only)

    Declaration

    Swift

    var hasChanges: Bool { get }

    Objective-C

    @property(nonatomic, readonly) BOOL hasChanges

    Discussion

    If you are observing this property using key-value observing (KVO) you should not touch the context or its objects within your implementation of observeValueForKeyPath:ofObject:change:context: for this notification. (This is because of the intricacy of the locations of the KVO notifications—for example, the context may be in the middle of an undo operation, or repairing a merge conflict.) If you need to send messages to the context or change any of its managed objects as a result of a change to the value of hasChanges, you must do so after the call stack unwinds (typically using performSelector:withObject:afterDelay: or a similar method).

    Special Considerations

    In OS X v10.6 and later, this property is key-value observing compliant.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

  • The persistent store coordinator of the receiver.

    Declaration

    Swift

    var persistentStoreCoordinator: NSPersistentStoreCoordinator?

    Objective-C

    @property(strong) NSPersistentStoreCoordinator *persistentStoreCoordinator

    Return Value

    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. May not be nil.

    Setting persistentStoreCoordinator to nil will raise an exception. If you want to “disconnect" a context from its persistent store coordinator, you should simply set all strong references to the context to nil and allow it to be deallocated normally.

    For more details, see Parent Store.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

  • The receiver’s parent context. (read-only)

    Declaration

    Swift

    var parentContext: NSManagedObjectContext?

    Objective-C

    @property(strong) NSManagedObjectContext *parentContext

    Discussion

    nil indicates there is no parent context. For more details, see Parent Store.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 5.0 and later

  • lock() - lock (iOS 8.0)

    Attempts to acquire a lock on the receiver.

    Declaration

    Swift

    func lock()

    Objective-C

    - (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 keep a strong reference to the context until it invokes unlock, otherwise if the context is deallocated this will result in deadlock.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

    Deprecated in iOS 8.0

  • unlock() - unlock (iOS 8.0)

    Relinquishes a previously acquired lock.

    Declaration

    Swift

    func unlock()

    Objective-C

    - (void)unlock

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

    Deprecated in iOS 8.0

  • tryLock() - tryLock (iOS 8.0)

    Attempts to acquire a lock.

    Declaration

    Swift

    func tryLock() -> Bool

    Objective-C

    - (BOOL)tryLock

    Return Value

    YEStrue if a lock was acquired, NOfalse otherwise.

    Discussion

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

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

    Deprecated in iOS 8.0

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

    Declaration

    Swift

    var propagatesDeletesAtEndOfEvent: Bool

    Objective-C

    @property(nonatomic) BOOL propagatesDeletesAtEndOfEvent

    Discussion

    YEStrue if the receiver propagates deletes at the end of the event in which a change was made, NOfalse if it propagates deletes only during a save operation. The default is YEStrue.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

  • A Boolean value that indicates whether the receiver keeps strong references to all registered managed objects.

    Declaration

    Swift

    var retainsRegisteredObjects: Bool

    Objective-C

    @property(nonatomic) BOOL retainsRegisteredObjects

    Discussion

    If set to YEStrue, the receiver keeps strong references to all registered managed objects. If set to NOfalse, then the receiver keeps strong references to registered objects only when they are inserted, updated, deleted, or locked. The default is NOfalse.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

  • The maximum length of time that may have elapsed since the store previously fetched data before fulfilling a fault issues a new fetch rather than using the previously-fetched data.

    Declaration

    Swift

    var stalenessInterval: NSTimeInterval

    Objective-C

    @property NSTimeInterval stalenessInterval

    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.

    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, because these stores maintain all current values in memory.

    The default is a negative value, which represents infinite staleness allowed. 0.0 represents “no staleness acceptable”.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

  • The merge policy of the receiver.

    Declaration

    Swift

    var mergePolicy: AnyObject

    Objective-C

    @property(strong) id mergePolicy

    Discussion

    The default is NSErrorMergePolicy. For possible values, see NSMergePolicy.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

  • Asynchronously performs a given block on the receiver’s queue.

    Declaration

    Swift

    func performBlock(_ block: () -> Void)

    Objective-C

    - (void)performBlock:(void (^)(void))block

    Parameters

    block

    The block to perform.

    Discussion

    You use this method to send messages to managed objects if the context was initialized using NSPrivateQueueConcurrencyType or NSMainQueueConcurrencyType.

    This method encapsulates an autorelease pool and a call to processPendingChanges.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 5.0 and later

  • Synchronously performs a given block on the receiver’s queue.

    Declaration

    Swift

    func performBlockAndWait(_ block: () -> Void)

    Objective-C

    - (void)performBlockAndWait:(void (^)(void))block

    Parameters

    block

    The block to perform.

    Discussion

    You use this method to send messages to managed objects if the context was initialized using NSPrivateQueueConcurrencyType or NSMainQueueConcurrencyType.

    This method may safely be called reentrantly.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 5.0 and later

  • userInfo userInfo Property

    The receiver’s user info.

    Declaration

    Swift

    var userInfo: NSMutableDictionary? { get }

    Objective-C

    @property(nonatomic, readonly, strong) NSMutableDictionary *userInfo

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 5.0 and later

Data Types

  • Constants to indicate the concurrency pattern with which a context will be used.

    Declaration

    Swift

    enum NSManagedObjectContextConcurrencyType : UInt { case ConfinementConcurrencyType case PrivateQueueConcurrencyType case MainQueueConcurrencyType }

    Objective-C

    enum { NSConfinementConcurrencyType = 0x00, NSPrivateQueueConcurrencyType = 0x01, NSMainQueueConcurrencyType = 0x02 }; typedef NSUInteger NSManagedObjectContextConcurrencyType;

    Constants

    • ConfinementConcurrencyType

      NSConfinementConcurrencyType

      Specifies that the context will use the thread confinement pattern.

      Available in iOS 5.0 and later

    • PrivateQueueConcurrencyType

      NSPrivateQueueConcurrencyType

      Specifies that the context will be associated with a private dispatch queue.

      Available in iOS 5.0 and later

    • MainQueueConcurrencyType

      NSMainQueueConcurrencyType

      Specifies that the context will be associated with the main queue.

      Available in iOS 5.0 and later

    Discussion

    See also initWithConcurrencyType: and Concurrency with Core Data.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 5.0 and later

  • Core Data uses these string constants as keys in the user info dictionary in a NSManagedObjectContextObjectsDidChangeNotification notification.

    Declaration

    Swift

    let NSInsertedObjectsKey: String let NSUpdatedObjectsKey: String let NSDeletedObjectsKey: String let NSRefreshedObjectsKey: String let NSInvalidatedObjectsKey: String let NSInvalidatedAllObjectsKey: String

    Objective-C

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

    Constants

    • NSInsertedObjectsKey

      NSInsertedObjectsKey

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

      Available in iOS 3.0 and later

    • NSUpdatedObjectsKey

      NSUpdatedObjectsKey

      Key for the set of objects that were updated.

      Available in iOS 3.0 and later

    • NSDeletedObjectsKey

      NSDeletedObjectsKey

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

      Available in iOS 3.0 and later

    • NSRefreshedObjectsKey

      NSRefreshedObjectsKey

      Key for the set of objects that were refreshed.

      Available in iOS 3.0 and later

    • NSInvalidatedObjectsKey

      NSInvalidatedObjectsKey

      Key for the set of objects that were invalidated.

      Available in iOS 3.0 and later

    • NSInvalidatedAllObjectsKey

      NSInvalidatedAllObjectsKey

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

      Available in iOS 3.0 and later

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

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

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

    You can only use the managed objects in this notification on the same thread on which it was posted.

    You can pass the notification object to mergeChangesFromContextDidSaveNotification: on another thread, however you must not use the managed object in the user info dictionary directly on another thread. For more details, see Concurrency with Core Data.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later

  • Posted whenever a managed object context is about to perform a save operation.

    The notification object is the managed object context. There is no userInfo dictionary.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later