Questions tagged [nsmanagedobjectcontext]

An instance of NSManagedObjectContext represents a single “object space”. 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. Available in iOS 3.0 and later in CoreData.

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

1384 questions
8
votes
2 answers

NSManagedObjectContext confusion

I am learning about CoreData. Obviously, one of the main classes you entouer is NSManagedObjectContext. I am unclear about the exact role of this. From the articles i've read, it seems that you can have multiple NSManagedObjectContexts. Does this…
0xSina
  • 20,973
  • 34
  • 136
  • 253
8
votes
3 answers

NSManagedObject changed properties after save

Is it possible to find out which properties were saved on a managed object after the save occurs? For example, I have someone listening for managed object context saves, (NSManagedObjectContextDidSaveNotification) and I want to know which…
JPC
  • 8,096
  • 22
  • 77
  • 110
8
votes
3 answers

NSUndoManager, Core Data and selective undo/redo

I'm working on a core data application that has a rather large hierarchy of managed objects similar to a tree. When a base object is created, it creates a few child objects which in turn create their own child objects and so on. Each of these child…
8
votes
1 answer

iPhone & Core Data - Removing NSManagedObject?

I'm trying to remove a managed object context, but instead of removing the object itself it sets all instant variables to null. Am I doing anything wrong while deleting an instant of NSManagedObjectContext? @implementation MyManagedObject -…
aryaxt
  • 76,198
  • 92
  • 293
  • 442
8
votes
2 answers

How to handle cleanup of external data when deleting *unsaved* Core Data objects?

In a managed object i have stored a path to an image file in the application's container. When the managed object get’s deleted, the image file should be moved to trash. This should be done as late as possible, so that i can provide undo…
MartinW
  • 4,966
  • 2
  • 24
  • 60
8
votes
3 answers

trying to save NSManagedObjectContext not working

I have been trying to figure out this problem for 2 days now. I keep getting an error when I try to save. //self.data is NSManagedObject. kAppDelegate.moc is the managed object context. self.data = [NSEntityDescription…
user3251270
  • 107
  • 1
  • 8
8
votes
1 answer

Core Data Error After Recreating Persistant Store

In my application, I have the ability to clear all data from the database. Once this operation completes, a bundled JSON is then parsed and then saved to the database (in order to return the database to the default state). The operation to parse and…
8
votes
2 answers

NSManagedObject's managedObjectContext property is nil

I'm trying to create a temporary managed object context, and after a few screens of the user putting in information, I merge that context with the main context (to ensure that there are no "incomplete" objects are inserted). This is how I create my…
Scott Berrevoets
  • 16,921
  • 6
  • 59
  • 80
8
votes
1 answer

Nested performBlock: on NSManagedObjectContext

When using NSPrivateQueueConcurrencyType and NSMainQueueConcurrencyType types for NSManagedObjectContext, is it safe to make nested performBlock calls on the same context ? [backgroundContext performBlock:^{ NSFetchRequest *myRequest = ...; …
FKDev
  • 2,266
  • 1
  • 20
  • 23
7
votes
2 answers

Does NSFetchedResultsController Observe All Changes to Persistent Store?

My program does work like link below: Update results of NSFetchedResultsController without a new fetch show result of NSFetchedResultsController to UITableView get new object from web service and store it to core data (in same view controller, with…
7
votes
5 answers

NSManagedObjectContext save doesn't crash but breaks on objc_exception_throw

I am having the same issue described at this address http://www.cocoabuilder.com/archive/cocoa/288659-iphone-nsmanagedobjectcontext-save-doesn-crash-but-breaks-on-objc-exception-throw.html I am debugging an application that uses Core Data with…
AmineG
  • 1,908
  • 2
  • 27
  • 43
7
votes
4 answers

What could cause mergeChangesFromContextDidSaveNotification not to merge/invalidate objects that have been updated?

[EDIT: simplified version of the question] mainMOC is the primary managed object context editorMOC is a managed object context created in editorViewController with an undo manager so the user can edit a single managed object after editorMOC saves,…
XJones
  • 21,959
  • 10
  • 67
  • 82
7
votes
1 answer

Core-Data: Parent context changes not being merged into child context

My situation is: I have a multi-threaded app with core-data database, managing multiple contexts. In my context Hieratchy I have a Root Saving Context, and child contexts where I fetch data and make/save changes. Context A -> Root parent context…
6rod9
  • 1,407
  • 12
  • 29
7
votes
1 answer

CoreData merge conflict shows managed object version change not data

I am have an entity in core data and I try to update it from two different context. I am storing managedObjectID of my managed object which I need to update as it is thread safe. Before updating my object I refresh the object to avoid merge…
7
votes
0 answers

CoreData Save Context Causing Crash When App Returns to Foreground. Swift

Okay so I am experiencing a frustrating issue that I would love some help or advice with. Basically I have an app that I'm developing that utilizes Core Data to store numerous user properties. What I have been doing for months during development,…
Pierce
  • 3,148
  • 16
  • 38