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
4
votes
4 answers

How to share a ManagedObjectContext when using UITabBarController with inner UINavigationControllers

I have an architectural question. My App uses a TabBarController right in the application window. The ApplicationDelegate creates the managedObjectContext, although it actually doesn't need it. Each ViewController in the TabBarController is a…
Czar
  • 356
  • 1
  • 4
  • 21
4
votes
2 answers

Passing a managedObjectContext through to a UITabBarController's views

I have an app which is based on the Utility template (where you flip over the view to see another). On the first view there is a login screen, then it flips over to reveal a UITabBar style interface. I'm having trouble working out how to pass the…
cannyboy
  • 24,180
  • 40
  • 146
  • 252
4
votes
2 answers

Can anyone give me some reference for this method "refreshAllObjects" in NSManagedObjectContext

[managedObjectContext refreshAllObjects] Actually I am getting random error sometime during save context and when I call [managedObjectContext refreshAllObjects] after error, it allows me to save. Could anyone please guide me about this method.
Vijay S
  • 185
  • 1
  • 7
4
votes
3 answers

Add an instance of NSManagedObject to NSManagedObjectContext ok, updating the same instance failed

I am using core data in my iPhone app. I have created a simple class Friend, which derives from NSManagedObject and which uses the following property: @property (nonatomic, retain) NSString *name; I am able to add and delete instances of this class…
4
votes
1 answer

Multiple NSManagedObjectContexts under one NSPersistentStoreCoordinator throws 'statement is still active' exception

I am changing my CoreData setup to have 2 NSManagedObjectContexts under 1 NSPersistentStoreCoordinator. The Root Context is NSManagedObjectContext instantiated with NSPrivateQueueConcurrencyType and set to NSMergeByPropertyStoreTrumpMergePolicy The…
Rpranata
  • 2,010
  • 18
  • 24
4
votes
1 answer

Core Data: NSObjectID and NSTemporaryObjectID leaks

Before I send my app to the App Store I like to check it for memory leaks and other fishy stuff with instruments. There is one Core Data issue that I can't seem to solve, so I've decided to create a small test app to illustrate the problem. What's…
Yvo
  • 18,681
  • 11
  • 71
  • 90
4
votes
1 answer

insertNewObjectForEntityForName: inManagedObjectContext: returning NSNumber bug?

I'm relatively well versed in CoreData and have been using it for several years with little or no difficulty. All of a sudden I'm now dumbfounded by an error. For the life of me, I can't figure out…
4
votes
3 answers

Iterate through NSManagedObjectContext objects?

I want to iterate through all of the objects in my NSManagedObjectContext, and update them manually. Then, every managed object should be updated. What's the best way to do this?
cactus
  • 41
  • 1
  • 2
4
votes
1 answer

CoreData occurred error on device but fine on simulator

I just tried using core data to do something, my goal is create a object with a child context, assign the values for an object, and then save it to storage after doing some operations. It works fine on simulator, but an error occurred when running…
4
votes
0 answers

Investigating an iOS crash report with EXC_BAD_ACCESS (SIGSEGV) and with ARM Thread State (64-bit)

I have recently released an update to my app in the App Store. The testing brought no crashes but I noticed when it was released in the App Store, that one scenario crashed my app on my 5s. This scenario was not crashing during development. I have…
4
votes
1 answer

When does NSManagedObject -managedObjectContext "return nil if the receiver has been deleted from its context"?

Apples documentation on NSManagedObject’s managedObjectContext method says: This method may return nil if the receiver has been deleted from its context. Does anyone know under what circumstances this method will return nil for a receiver that…
4
votes
0 answers

Calling mergeChangesFromContextDidSaveNotification: Not Triggering mocObjectsDidChangeNotification in Main Context

This system uses the multi-threaded Core Data configuration of two contexts, shared persistent store. I have an MOC created on the main thread of type NSMainQueueConcurrencyType (MOC A). There is an observer registered for…
Kreeble Song
  • 121
  • 1
  • 8
4
votes
1 answer

Core Data: editing object from detail view

I'm just starting out with Core Data and I have an iPhone Core Data project set up in a master-detail view system. The master view contains items, and the detail view lets you edit the properties of the selected item. I'm looking for the best…
indragie
  • 18,002
  • 16
  • 95
  • 164
4
votes
1 answer

Create temporary CoreData entities (in a non-persistent MagicalRecord context)?

I simply want to create entities yet not to be saved, only inspect them. Can I create a temporary context for those? Is there a way to move them into the persistent context once I decided to store them? And the point: are these features available…
Geri Borbás
  • 15,810
  • 18
  • 109
  • 172
4
votes
1 answer

Track attribute change of NSManagedObject

I'm looking for a way to track the attribute change of an NSManagedObject. Currently I use a NSNotifactionCenter to see the changes of my managedobjectcontext: [[NSNotificationCenter defaultCenter] addObserver:self…
arnoapp
  • 2,416
  • 4
  • 38
  • 70