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
10
votes
3 answers

Why doesn't NSManagedObject instances hold a strong reference to their NSManagedObjectContext?

As pointed out in another question on SO (and the Apple docs), NSManagedObject instances do not hold a strong reference to the NSManagedObjectContext from which they originated. On first blush, this seems like a strange decision, since…
10
votes
1 answer

Cross-model relationships in NSManagedObjectModel from merged models?

Is it possible to model relationships between entities that are defined in separate NSManagedObjectModels if the entities are always used within an NSManagedObjectModel that is created by merging the relevant models? For example, say model 1 defines…
Barry Wark
  • 107,306
  • 24
  • 181
  • 206
9
votes
2 answers

Performance of NSManagedObjectContext save degrades dramatically

I am having issues with a CoreData-based iOS app when it tries to build the initial DB from data sent from the server. Basically, the server sends down 1MB chunks of objects (about 3,000 per chunk), and the iOS client deserializes them and writes…
glenc
  • 3,132
  • 2
  • 26
  • 42
9
votes
2 answers

How to ignore changes in mergeChangesFromContextDidSaveNotification in NSManagedObjectContextWillSaveNotification

I am using a Private Managed Object Context to create some new objects into the persistent store, then after saving the private MOC, merging them into the main MOC using mergeChangesFromContextDidSaveNotification. This works fine, and updates the UI…
Z S
  • 7,039
  • 12
  • 53
  • 105
9
votes
1 answer

Core Data: should I be fetching objects from the parent context or does the child context have the same objects as the parent?

I am slightly confused about parent/child contexts for ManagedObjectContext. When I setup a child context and set the parent context, does the child context contain all the objects of the parent context? I am using the stock Core Data methods that…
The Nomad
  • 7,155
  • 14
  • 65
  • 100
9
votes
2 answers

How to test Core Data properly in Swift

There are quite a few subjects on this already, but I have yet to find a solution that is workable for Swift (Xcode 6.2). To test Core Data backed classes in Swift, I generate new Managed Object Contexts that I then inject into my classes. //Given…
Dandy
  • 1,203
  • 1
  • 16
  • 31
9
votes
4 answers

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. For the life of me, I can't figure out why insertNewObjectForEntityForName:inManagedObjectContext: is all of a sudden returning some sort…
9
votes
3 answers

Core data find-or-create most efficient way

I have around 10000 objects of entity 'Message'. When I add a new 'Message' i want to first see whether it exists - and if it does just update it's data, but if it doesn't to create it. Right now the "find-or-create" algorithm works with by saving…
9
votes
1 answer

Core Data Object IDs vs Permanent Object ID

This question might look like it's been asked many times before, but I'm not sure I've aggregated the answer correctly. So here goes. ObjectIDs are described by Apple (WWDC 2012 Session 214) as context-safe, thread-safe. So I spent some time…
9
votes
1 answer

Core Data managed object context design recommendation

We are working on an Enterprise-level application, which will store tens of thousands of objects with Core Data, and we are having issues on several fronts. Our application has several independent systems which operate on the data when needed.…
Léo Natan
  • 56,823
  • 9
  • 150
  • 195
9
votes
1 answer

existingObjectWithID:error: returns nil, but objectWithID: returns an actual usable object

My understanding from the documentation and from this answer is that if the data exists, NSManagedObjectContext's existingObjectWithID:error: and objectWithID: methods should return the same object, but when the data doesn't exist,…
Isaac
  • 10,668
  • 5
  • 59
  • 68
9
votes
2 answers

Saving Single CoreData Entity (Not the Whole Context) While Keeping NSFetchedResultController Functionality

Phew, sorry for the long title. I have a single Managed Object Context where I am storing songs derived from two different locations. I get some of the songs from the persistent storage on the phone (using Core Data), and I pull some of the songs…
9
votes
1 answer

undo all changes made in the child view controller

There are two entities: Author and Book. Author has an attribute authorName and a to-many relationships books. Book has several attributes and a relationship author. There is a view controller (VCAuthor) to edit an Author object. The child view…
lu yuan
  • 7,207
  • 9
  • 44
  • 78
9
votes
4 answers

Create an NSManagedObject Without Saving?

Possible Duplicate: Store But Don't Save NSManagedObject to CoreData? I need to make an NSManagedObject without saving it, how can I do this? The reason I want to do this is the app has a setup in which the user enters their details, however I…
Josh Kahane
  • 16,765
  • 45
  • 140
  • 253
8
votes
1 answer

CoreData fails to save context, saying relationship is nil - however it is definitely set

When I attempt to save the context of my CoreData model, I receive an error Unresolved error Error Domain=NSCocoaErrorDomain Code=1560 "The operation couldn’t be completed. (Cocoa error 1560.)" UserInfo=0x76924b0 {NSDetailedErrors=( "Error…
Onedayitwillmake
  • 711
  • 1
  • 10
  • 19