<!--
{
  "availability" : [
    "iOS: 3.0.0 -",
    "iPadOS: 3.0.0 -",
    "macCatalyst: 13.1.0 -",
    "macOS: 10.4.0 -",
    "tvOS: -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "CoreData",
  "identifier" : "/documentation/CoreData/NSManagedObjectContext",
  "metadataVersion" : "0.1.0",
  "role" : "Class",
  "symbol" : {
    "kind" : "Class",
    "modules" : [
      "Core Data"
    ],
    "preciseIdentifier" : "c:objc(cs)NSManagedObjectContext"
  },
  "title" : "NSManagedObjectContext"
}
-->

# NSManagedObjectContext

An object space to manipulate and track changes to managed objects.

```
nonisolated class NSManagedObjectContext
```

## Overview

A context consists of a group of related model objects that represent an internally consistent view of one or more persistent stores. Changes to managed objects remain in memory in the associated context until Core Data saves that context to 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. Therefore, an object is unique 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 macOS 10.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`](/documentation/CoreData/NSManagedObjectContext#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 <doc://com.apple.documentation/documentation/Foundation/NSNotification/Name-swift.struct/NSManagedObjectContextObjectsDidChange> for example. Typically, you should register to receive these notifications only from known contexts:

```objc
[[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 <doc://com.apple.documentation/documentation/Foundation/NotificationCenter/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 [Core Data Programming Guide](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreData/index.html#//apple_ref/doc/uid/TP40001075)). A consequence of this is that a context assumes the default owner is the thread or queue that creates it. Don’t, therefore, initialize a context on one thread then pass it to another. Instead, pass a reference to a persistent store coordinator and have the receiving thread or queue create a new context using that. If you use <doc://com.apple.documentation/documentation/Foundation/Operation>, you must create the context in <doc://com.apple.documentation/documentation/Foundation/Operation/main()> (for a serial queue) or <doc://com.apple.documentation/documentation/Foundation/Operation/start()> (for a concurrent queue).

When you create a context you specify the concurrency type with which you’ll use it. When you create a managed object context, you have two options for its thread (queue) association:

- Private: The context creates and manages a private queue.
- Main: The context associates with the main queue and is dependent on the application’s event loop; otherwise, it’s similar to a private context. Use this type for contexts that update view controllers and other user interface elements.

You use contexts using the queue-based concurrency types in conjunction with [`perform(_:)`](/documentation/CoreData/NSManagedObjectContext/perform(_:)) and [`performAndWait(_:)`](/documentation/CoreData/NSManagedObjectContext/performAndWait(_:)-ypye). 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 executes on the main thread, you can invoke methods on the main queue style contexts directly instead of using the block based API.

[`perform(_:)`](/documentation/CoreData/NSManagedObjectContext/perform(_:)) and [`performAndWait(_:)`](/documentation/CoreData/NSManagedObjectContext/performAndWait(_:)-ypye) ensure the block operations execute on the correct queue for the context. The [`perform(_:)`](/documentation/CoreData/NSManagedObjectContext/perform(_:)) method returns immediately and the context executes the block methods on its own thread. With the [`performAndWait(_:)`](/documentation/CoreData/NSManagedObjectContext/performAndWait(_:)-ypye) method, the context still executes the block methods on its own thread, but the method doesn’t return until the block completes.

It’s important to appreciate that blocks execute 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()`](/documentation/CoreData/NSManagedObjectContext/save()).

```objc
__block BOOL savedOK = NO;
[managedObjectContext performBlockAndWait:^{

    // Perform operations with the context.

    NSError *error = nil;
    if ([managedObjectContext save:&error]) {
        savedOK = YES;
    } else {
        NSLog(@"Error saving: %@", error);
    }
}];
```

You can also perform other operations, such as:

```objc
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Entity"];
__block NSUInteger count = 0;

[managedObjectContext performBlockAndWait:^() {
    NSError *error;
    count = [managedObjectContext countForFetchRequest:fetchRequest error:&error];
    if (count == NSNotFound) {
        NSLog(@"Error counting objects: %@", error);
    }
}];

NSLog(@"The fetch request would return %lu objects", count);
```

### 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()`](/documentation/CoreData/NSManagedObjectContext/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`).

## Topics

### Creating a context

[`init(_:)`](/documentation/CoreData/NSManagedObjectContext/init(_:))

Creates a context that uses the specified concurrency type.

[`ConcurrencyType`](/documentation/CoreData/NSManagedObjectContext/ConcurrencyType-swift.struct)

The concurrency types to use with a managed object context.

[`-  initWithConcurrencyType:`](/documentation/CoreData/NSManagedObjectContext/init(concurrencyType:))

Creates a context that uses the specified concurrency type.

[`NSManagedObjectContextConcurrencyType`](/documentation/CoreData/NSManagedObjectContextConcurrencyType)

The concurrency types you can use with a managed object context.

### Configuring a context

[`persistentStoreCoordinator`](/documentation/CoreData/NSManagedObjectContext/persistentStoreCoordinator)

The persistent store coordinator of the context.

[`parentContext`](/documentation/CoreData/NSManagedObjectContext/parent)

The parent of the context.

[`name`](/documentation/CoreData/NSManagedObjectContext/name)

The developer-provided name of the context.

[`userInfo`](/documentation/CoreData/NSManagedObjectContext/userInfo)

The user information for the context.

### Registering and fetching objects

[`fetch(_:)`](/documentation/CoreData/NSManagedObjectContext/fetch(_:)-38ys1)

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

[`fetch(_:)`](/documentation/CoreData/NSManagedObjectContext/fetch(_:)-4xeoz)

Returns an array of items of the specified type that meet the fetch request’s critieria.

[`-  executeFetchRequest:error:`](/documentation/CoreData/NSManagedObjectContext/executeFetchRequest:error:)

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

[`-  countForFetchRequest:error:`](/documentation/CoreData/NSManagedObjectContext/count(for:)-93zbm)

Returns the number of objects the specified request fetches when it executes.

[`-  objectRegisteredForID:`](/documentation/CoreData/NSManagedObjectContext/registeredObject(for:))

Returns an object that exists in the context.

[`-  objectWithID:`](/documentation/CoreData/NSManagedObjectContext/object(with:))

Returns either an existing object from the context or a fault that represents that object.

[`-  existingObjectWithID:error:`](/documentation/CoreData/NSManagedObjectContext/existingObject(with:))

Returns an existing object from either the context or the persistent store.

[`registeredObjects`](/documentation/CoreData/NSManagedObjectContext/registeredObjects)

The set of registered managed objects in the context.

[`count(for:)`](/documentation/CoreData/NSManagedObjectContext/count(for:)-3r91z)

Returns a count of the objects the specified request fetches when it executes.

[`-  executeRequest:error:`](/documentation/CoreData/NSManagedObjectContext/execute(_:))

Passes a request to the persistent store without affecting the contents of the managed object context, and returns a persistent store result.

[`-  refreshAllObjects`](/documentation/CoreData/NSManagedObjectContext/refreshAllObjects())

Refreshes all of the registered managed objects in the context.

[`retainsRegisteredObjects`](/documentation/CoreData/NSManagedObjectContext/retainsRegisteredObjects)

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

### Handling managed objects

[`shouldDeleteInaccessibleFaults`](/documentation/CoreData/NSManagedObjectContext/shouldDeleteInaccessibleFaults)

A Boolean value that determines whether the context turns inaccessible faults into deleted objects.

[`insertedObjects`](/documentation/CoreData/NSManagedObjectContext/insertedObjects)

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

[`updatedObjects`](/documentation/CoreData/NSManagedObjectContext/updatedObjects)

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

[`deletedObjects`](/documentation/CoreData/NSManagedObjectContext/deletedObjects)

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

[`-  shouldHandleInaccessibleFault:forObjectID:triggeredByProperty:`](/documentation/CoreData/NSManagedObjectContext/shouldHandleInaccessibleFault(_:for:triggeredByProperty:))

Creates a log of the inaccessible fault.

[`-  insertObject:`](/documentation/CoreData/NSManagedObjectContext/insert(_:))

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

[`-  deleteObject:`](/documentation/CoreData/NSManagedObjectContext/delete(_:))

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

[`-  assignObject:toPersistentStore:`](/documentation/CoreData/NSManagedObjectContext/assign(_:to:))

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

[`-  obtainPermanentIDsForObjects:error:`](/documentation/CoreData/NSManagedObjectContext/obtainPermanentIDs(for:))

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

[`-  detectConflictsForObject:`](/documentation/CoreData/NSManagedObjectContext/detectConflicts(for:))

Marks an object for conflict detection.

[`-  refreshObject:mergeChanges:`](/documentation/CoreData/NSManagedObjectContext/refresh(_:mergeChanges:))

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

[`-  processPendingChanges`](/documentation/CoreData/NSManagedObjectContext/processPendingChanges())

Forces the context to process changes to the object graph.

[`-  observeValueForKeyPath:ofObject:change:context:`](/documentation/CoreData/NSManagedObjectContext/observeValue(forKeyPath:of:change:context:))

Allows a context that has registered as an observer of a value to be notified of a change to that value.

### Managing concurrency

[`NSManagedObjectContextQueryGenerationKey`](/documentation/CoreData/NSManagedObjectContextQueryGenerationKey)

Constant used to reference the query generation token.

[`+  mergeChangesFromRemoteContextSave:intoContexts:`](/documentation/CoreData/NSManagedObjectContext/mergeChanges(fromRemoteContextSave:into:))

Handles changes from other processes or from a serialized state.

[`automaticallyMergesChangesFromParent`](/documentation/CoreData/NSManagedObjectContext/automaticallyMergesChangesFromParent)

A Boolean value that indicates whether the context automatically merges changes saved to its persistent store coordinator or parent context.

[`concurrencyType`](/documentation/CoreData/NSManagedObjectContext/concurrencyType-swift.property)

The concurrency type for the context.

[`mergePolicy`](/documentation/CoreData/NSManagedObjectContext/mergePolicy)

The merge policy of the context.

[`queryGenerationToken`](/documentation/CoreData/NSManagedObjectContext/queryGenerationToken)

Returns the token associated with the query generation currently in use by this context.

[`transactionAuthor`](/documentation/CoreData/NSManagedObjectContext/transactionAuthor)

The author for the context that is used as an identifier in persistent history transactions.

[`-  mergeChangesFromContextDidSaveNotification:`](/documentation/CoreData/NSManagedObjectContext/mergeChanges(fromContextDidSave:))

Merges the changes specified in a given notification.

[`-  setQueryGenerationFromToken:error:`](/documentation/CoreData/NSManagedObjectContext/setQueryGenerationFrom(_:))

Sets the query generation this context should use.

### Managing notifications

[`didChangeObjectsNotification`](/documentation/CoreData/NSManagedObjectContext/didChangeObjectsNotification)

A notification that posts when a context makes changes to its registered objects.

  <doc://com.apple.documentation/documentation/Foundation/NSNotification/Name-swift.struct/NSManagedObjectContextObjectsDidChange>

[`didSaveObjectsNotification`](/documentation/CoreData/NSManagedObjectContext/didSaveObjectsNotification)

A notification that posts after a context completes a save.

  <doc://com.apple.documentation/documentation/Foundation/NSNotification/Name-swift.struct/NSManagedObjectContextDidSave>

[`willSaveObjectsNotification`](/documentation/CoreData/NSManagedObjectContext/willSaveObjectsNotification)

A notification that posts before a context writes pending changes to disk.

  <doc://com.apple.documentation/documentation/Foundation/NSNotification/Name-swift.struct/NSManagedObjectContextWillSave>

[`NSManagedObjectContextObjectsDidChangeNotification`](/documentation/CoreData/NSManagedObjectContextObjectsDidChangeNotification)

A notification that posts when there are changes to context’s registered managed objects.

[`NSManagedObjectContextDidSaveNotification`](/documentation/CoreData/NSManagedObjectContextDidSaveNotification)

A notification that posts after a context finishes writing unsaved changes.

[`NSManagedObjectContextWillSaveNotification`](/documentation/CoreData/NSManagedObjectContextWillSaveNotification)

A notification that posts before a context writes unsaved changes.

[`NSManagedObjectContextDidMergeChangesObjectIDsNotification`](/documentation/CoreData/NSManagedObjectContextDidMergeChangesObjectIDsNotification)

[`NSManagedObjectContextDidSaveObjectIDsNotification`](/documentation/CoreData/NSManagedObjectContextDidSaveObjectIDsNotification)

A notification that posts after a context finishes writing changes.

[`NSInsertedObjectsKey`](/documentation/CoreData/NSInsertedObjectsKey)

A key for the set of objects that were inserted into the context.

[`NSUpdatedObjectsKey`](/documentation/CoreData/NSUpdatedObjectsKey)

A key for the set of objects that were updated.

[`NSDeletedObjectsKey`](/documentation/CoreData/NSDeletedObjectsKey)

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

[`NSRefreshedObjectsKey`](/documentation/CoreData/NSRefreshedObjectsKey)

A key for the set of objects that were refreshed but were not dirtied in the scope of this context.

[`NSInvalidatedObjectsKey`](/documentation/CoreData/NSInvalidatedObjectsKey)

A key for the set of objects that were invalidated.

[`NSInvalidatedAllObjectsKey`](/documentation/CoreData/NSInvalidatedAllObjectsKey)

A key that specifies that all objects in the context have been invalidated.

[`didMergeChangesObjectIDsNotification`](/documentation/CoreData/NSManagedObjectContext/didMergeChangesObjectIDsNotification)

A notification that posts after a context finishes merging changes from another notification.

[`didSaveObjectIDsNotification`](/documentation/CoreData/NSManagedObjectContext/didSaveObjectIDsNotification)

A notification that posts after a context finishes saving changes to its managed objects.

[`NotificationKey`](/documentation/CoreData/NSManagedObjectContext/NotificationKey)

Keys to access details in user info dictionaries of managed object context notifications.

### Managing unsaved and uncommitted changes

[`-  save:`](/documentation/CoreData/NSManagedObjectContext/save())

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

[`hasChanges`](/documentation/CoreData/NSManagedObjectContext/hasChanges)

A Boolean value that indicates whether the context has uncommitted changes.

### Undoing changes

[`undoManager`](/documentation/CoreData/NSManagedObjectContext/undoManager)

The object that provides undo support for the context.

[`-  undo`](/documentation/CoreData/NSManagedObjectContext/undo())

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

[`-  redo`](/documentation/CoreData/NSManagedObjectContext/redo())

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

[`-  reset`](/documentation/CoreData/NSManagedObjectContext/reset())

Returns the context to its base state.

[`-  rollback`](/documentation/CoreData/NSManagedObjectContext/rollback())

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

### Handling delete propagation

[`propagatesDeletesAtEndOfEvent`](/documentation/CoreData/NSManagedObjectContext/propagatesDeletesAtEndOfEvent)

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

### Managing the staleness interval

[`stalenessInterval`](/documentation/CoreData/NSManagedObjectContext/stalenessInterval)

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

### Performing block operations

[`-  performBlock:`](/documentation/CoreData/NSManagedObjectContext/perform(_:))

Asynchronously performs the specified closure on the context’s queue.

[`perform(schedule:_:)`](/documentation/CoreData/NSManagedObjectContext/perform(schedule:_:))

Submits a closure to the context’s queue for asynchronous execution.

[`-  performBlockAndWait:`](/documentation/CoreData/NSManagedObjectContext/performAndWait(_:)-ypye)

Synchronously performs the specified closure on the context’s queue.

[`performAndWait(_:)`](/documentation/CoreData/NSManagedObjectContext/performAndWait(_:)-6aaf1)

Submits a closure to the context’s queue for synchronous execution.

[`ScheduledTaskType`](/documentation/CoreData/NSManagedObjectContext/ScheduledTaskType)

The different types of scheduled tasks.

### Deprecated

[Deprecated symbols](/documentation/CoreData/nsmanagedobjectcontext-deprecated-symbols)

Review unsupported symbols and their replacements.

## Relationships

### Conforms To

[`Hashable`](/documentation/Swift/Hashable)

[`Sendable`](/documentation/Swift/Sendable)

[`Escapable`](/documentation/Swift/Escapable)

[`NSEditorRegistration`](/documentation/AppKit/NSEditorRegistration)

[`NSCoding`](/documentation/Foundation/NSCoding)

[`Copyable`](/documentation/Swift/Copyable)

[`CVarArg`](/documentation/Swift/CVarArg)

[`NSLocking`](/documentation/Foundation/NSLocking)

[`SendableMetatype`](/documentation/Swift/SendableMetatype)

[`CustomDebugStringConvertible`](/documentation/Swift/CustomDebugStringConvertible)

[`CustomStringConvertible`](/documentation/Swift/CustomStringConvertible)

[`NSEditor`](/documentation/AppKit/NSEditor)

[`Equatable`](/documentation/Swift/Equatable)

[`NSObjectProtocol`](/documentation/ObjectiveC/NSObjectProtocol)

### Inherits From

[`NSObject-swift.class`](/documentation/ObjectiveC/NSObject-swift.class)

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)