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
0
votes
1 answer

NSFetchedResultsController requires a non-nil fetch request and managedObjectContext error

Using core data on a on an application that has tabbed views. The second tab loads the core data, no errors show up in Xcode or when I run the app but when I click on the second tab the app crashes with the error "An Instance of…
0
votes
1 answer

Relationship between NSManagedObject across multiple NSManagedObjectContexts

My application uses multiple threads with one managed object context per thread. For clarity I will refer to the different managed object contexts as: moc1, moc2, ..., etc. Let's assume we have two models with a simple one-many relationship: User…
0
votes
2 answers

Reference count of Managed Objects

I have class A (subclass of NSManagedObject) that has a property of class B (also subclass of NSManagedObject), the property is @synthesize not @dynamic, there is no relationship between A and B in my model, I just want that A will keep a reference…
0
votes
2 answers

undo all changes made in a view controller

Is it possible to undo all changes made in a view controller without affecting the changes made in its parent view controller? btw. They are with the same managedObjectContext. ps. I have two entities A and B. A has an to-many relationships to B.…
lu yuan
  • 7,207
  • 9
  • 44
  • 78
0
votes
1 answer

App becomes unresponsive on NSFetchRequests

I have the above CoreData Model in my first iPad app. I'm building a filtering system in a TableViewController as shown below. The problem is that whenever I make a UI change, toggle a switch of tap a button, My UI becomes non-responsive for a…
0
votes
2 answers

Passing NSManagedObjectContext context to ViewController is nil

I've used the following code to pass a context to a ViewController in the pass without issue but for some reason it is behaving differently for this project. User performs an action I load the ViewController like so: ProjectListViewController…
Allfocus
  • 293
  • 1
  • 5
  • 14
0
votes
1 answer

Fetching Core Data Related Objects

I have a Core data entity called day that has a to-one relationship with another entity named spot named spotTable. I fetched a day record and i want to access the spot object related to my day instance i accessed it like this: self.spotTable =…
0
votes
1 answer

CoreData: how to populate array (getting by parse XML components ) and save them using CoreData, in iphone

One project that I was trying to do was developing an XML parser to parse XML components and save them using CoreData, as well as showing them through TableView. already I did parse the data from xml file. and Saved the parsed data in to 3…
Ranga
  • 821
  • 4
  • 11
  • 20
0
votes
1 answer

Not able to modaly push tableView containing Core-Data data

I've managed to create a tableViewController inside a NavigationController (using the CoreDataTableViewController from Stanford University) with data loaded via Core-Data. The user can check some parameters, set defaults, etc. It works pretty well…
Marcal
  • 1,371
  • 5
  • 19
  • 37
0
votes
1 answer

Understanding adding/updating relational objects in Core Data

I have , for example, two entities called Class and Student. Both entities are connected by a One-To-Many relationship, "Class" has a ClassID field and Student has both a ClassID and StudentID fields. I have a couple of questions on this…
Shai Mishali
  • 9,224
  • 4
  • 56
  • 83
0
votes
1 answer

Debugging NSArrayController bound to NSManagedObjectContext

I've an NSManagedObjectContext with two entities, A and B. I've an NSArrayController bound to the NSManagedObjectContext and an NSTableView. The NSArrayController is set to list entities of type B. The array controller then feeds the table view. The…
0
votes
1 answer

OCMock - trying to mock NSEntityDescription

in order to test a managed class I tried to create an instance in a unit test by first trying to mock NSEntityDescription and NSManagedObjectContext. id mockEntityDesc = [OCMockObject niceMockForClass:[NSEntityDescription class]]; id…
-1
votes
2 answers

Testing Core Data on iPhone without connection to Xcode

Running the App on the iPhone works fine, but only if it stays connected to the Mac/linked to Xcode. If I try to run it after I disconnected it (after stopping the Run), Core Data does not work anymore. Neither the Build nor the Debug configuration…
saeppi
  • 259
  • 4
  • 16
-1
votes
1 answer

Mixing parent and child managed object contexts down a view hierarchy

I'm using Core Data to persist data in my app, and have a question about mixing parent and child managed object contexts down a view hierarchy. For simplicity, let's say my app allows users to create a library of recipes they've come up with. In the…
-1
votes
2 answers

Is viewContext different between Swift and SwiftUI

EDIT: I've added a rewording of my question at the bottom. So I have an app that I've been working on for a long time. I used it to teach myself Xcode / Swift and now that I have a Mac again, I'm trying to learn SwiftUI as well by remaking the app…
Jason Brady
  • 1,560
  • 1
  • 17
  • 40