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
6
votes
2 answers

what's the 'proper' way to use NSManagedObjectContext's objectWithID:

the docs state: ...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 …
lulu
  • 669
  • 10
  • 26
6
votes
3 answers

How to get the ID of an object saved to Core Data's managed object context?

I have this code: NSEntityDescription *userEntity = [[[engine managedObjectModel] entitiesByName] objectForKey:@"User"]; User *user = [[User alloc] initWithEntity:userEntity insertIntoManagedObjectContext:[engine managedObjectContext]]; and I want…
Spanky
  • 4,980
  • 7
  • 36
  • 37
6
votes
2 answers

Swift get specific NSManagedObject from entity (core data)

I have an entity in my "ProjName.xcdatamodel" with the name "Questions". In this entity I have 5 attributes ("icehockey","volleyball","soccer",...), each with type transformable. Each row (attribute) will be filled with a NSMutableArray. What I want…
user2099024
  • 1,452
  • 4
  • 16
  • 26
6
votes
4 answers

Core Data: parent context blocks child

I'm doing some background processing in an app with core data. The background processing is done on a child managedObjectContext. Context initialization: appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate // the moc in…
tzer
  • 280
  • 4
  • 11
6
votes
1 answer

Retrieve NSManagedObjectContext from NSManagedObject

I've looked for this solution for a while, and I've always given up and found a work around, but does anyone know how do find the NSManagedObjectContext from an instance of an NSManagedObject? I am currently using 3 contexts, and I would like to…
coder
  • 10,460
  • 17
  • 72
  • 125
6
votes
3 answers

Using NSManagedObject subclasses to transport persistent and non persistent data

I'm having some thoughts on how to use some core data's NSManagedObject subclasses to handle persistent data and non persistent data. Let's say you have a recipe app displaying a list of your own recipes from CoreData and in this same app you can…
6
votes
2 answers

Core data Multi level parent - Child context

In my app I have UITableViewController that shows event list. This controller uses ManagedObjectContext Say ParentContext. Now if any Event is selected, then a detailed View Controller is shown where users can edit the details of Event. So i have…
krishnan
  • 782
  • 1
  • 9
  • 20
6
votes
1 answer

Debugging in XCode: Exception Breakpoints

I'm debugging a random SIGTRAP crash right now that just happens in the background. It's probably something that has to do with an NSManagedObjectContext somewhere. Besides that, I'm trying to debug it using an exception breakpoint to at least find…
jakenberg
  • 2,125
  • 20
  • 38
6
votes
2 answers

performBlockAndWait creates deadlock

I am writing a function that performs some CoreData stuff. I want the function to return only after all the CoreData operations have executed. The CoreData stuff involves creating an object in a background context, then doing some more stuff in the…
6
votes
2 answers

Store But Don't Save NSManagedObject to CoreData?

I have a short setup process in my app and I create an NSManagedObject to store name and other details of an individual, however during this setup I don't want to save the object until the user presses 'Done' right at the end of the setup (just…
Josh Kahane
  • 16,765
  • 45
  • 140
  • 253
5
votes
4 answers

Copying pending changes between NSManagedObjectContexts with shared persistent store?

I have two instances of NSManagedObjectContext: one is used in main thread and the other is used in a background thread (via an NSOperation.) For thread safety, these two contexts only share an NSPersistentStoreCoordinator. The problem I'm having is…
5
votes
1 answer

Duplication of entity when change made by a child ManagedObjectContext is pushed (saved) to its parent

I expect (hope even) that this will be a stupid question, but after wrestling for many hours with this problem I need some insight. My iOS 5.1 app uses nested MOCs, having a PrivateQueueConcurrency child MOC, call it MOC-Child, whose parent is a…
5
votes
3 answers

Does an NSManagedObject retain its NSManagedObjectContext?

NSManagedObject provides access to its NSManagedObjectContext, but does it retain it? According to "Passing Around a NSManagedObjectContext on iOS" by Marcus Zarra, "The NSManagedObject retains a reference to its NSManagedObjectContext internally…
ma11hew28
  • 121,420
  • 116
  • 450
  • 651
5
votes
2 answers

Core Data: Observing new Entity of certain type

I would like to be notified whenever an entity of a certain type is added (and maybe changed/removed). I read it is possible by adding an observer to the managedObjectContext. However, I haven't found an actual way to do it. I am doing: [context…
rufo
  • 5,158
  • 2
  • 36
  • 47
5
votes
3 answers

NSManagedObjectContext doesn't refresh correctly

hi :) I have a similarly issue like in Working with the same NSManagedObjectContext in multiple tabs background: My managedObjectContext (further MOC) is initialised in my appDelegate class and passed throught to multiple tabs by…
geo
  • 1,781
  • 1
  • 18
  • 30