What The Context ? The Managed Object Context
The Managed Object Context is the epicentre of all Core data Programming. Its strewn in every sentence while learning CoreData and finds itself between most of the method calls in a CoreData driven application.
But what exactly is a context ?Â
Its crucial for anyone trying to learn CoreData programming to be able to picture what a context is. Context is better understood as something that is, rather than what it does.
So what it is ?Â
A Managed Object Context is a space in RAM or fast memory.
Thats it ! You could probably close this tab and move on, because this blogs purpose has been fulfilled.Â
Okay for those of you who want to stick around and know more.
A context is a space in fast memory which allows faster read and write, so that data can be retrieved and stored faster during an applications life cycle to provide a smooth user experience and can only be persisted when necessary. Hereâs a pictorial representation to help you understand better.
As you can see, there are three main regions for any CoreData driven application. There is the persistent Store which is most probably an SQLite database in iOS which lies at the very end of any application, there is your applicationâs UI which lies right at the top level and in-between these two lies the the RAM which contains a space called the managed object context.Â
Now obviously the managed object context is just not a space in RAM. Its actually an API to manage that space in RAM, meaning it contains methods and variables and a whole lot of other stuff to manage that space in RAM. Conventionally when you start a project with CoreData selected, there is a whole bunch of boiler plate code in your AppDelegate files which sets up your persistent store and managed Object Context.Â
After your SQLite database has been set up, a space in RAM is also set aside for the Managed Object Context.
Assuming you have done a bit of CoreData programming, There are a set of imperative code you write for an CoreData driven application.Â
Hereâs a picture depicting some of the functions that are performed throughout your application.
                Inserting Objects
When the need to persist data occurs the first method usually written is
[NSEntityDescription insertNewObjectForEntityForName:@"Your entity
Name" inManagedObjectContext:self.managedObjectContext];
If you draw your attention to only the name of this method, you can see the part insertNewObjectForEntityForName which means create managed objects of the model class having a name @"Your entity Name" and if you notice the last part inManagedObjectContext, it actually means store these objects in the context that you provide through the parameter.
This method returns a pointer to that managed object, just created in that space in RAM and you can now go ahead and treat this as an object.Â
(Note: any object that belongs to Managed Object Context is referred to as a managed object.)Â
So your new managed object now lies in RAM, inside a space given to your Managed Object Context. But as we all now, that any object will be flushed away if its not persisted.Â
Hence the second method call
 [self.managedObjectContext save:&error]Â
As its now evident that we need to tell the context to take this object we now created and store it permanently in your persistent store file which mostly is an SQLite database.Â
This method returns a BOOL of YES or NO stating whether the save was successful or not, and takes a pointer of an NSError to debug incase if the save was not successful. This causes the managed objects information to be written and stored permanently in your SQLite database.Â
Does this mean the managed object is removed from the Managed Object Context ?Â
NO ! Your object still lies in the Managed Object Context.
                   FETCHING
Now you have saved a whole lot of objects in the database, its time to fetchâem.
Lets take a look at how fetching works.Â
While Fetching managed objects there are two main criteriaâs you need to specify to fulfil a fetch.
What are you looking for ?
Where do you want to look ?
The first part is handled by an instance of a NSFetchRequest which specifies what class does the managed objects your looking for belong and are there any particular kind of managed objects you need .
Heres an example :Â
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Your entity name"];Â
Here your specifying what class does the managed objects you need belong too.
An instance of NSFetchRequest also has references to instances of NSPredicate which tells what kind of objects are you looking for, in other words your search criteria. And an instance of NSSortDescriptor which specifies any sorting order you need for these managed objects.Â
This completes the first part of what managed objects you need. Now moving on to where to look for the objects.Â
This is the most important part, where do you find these objects you are looking for? Obviously the same place you created them, in a Managed Object Context.
Hence you tell the Managed Object Context to execute a fetch request which contains what is your search criteria so that it can look around in that memory space in has in the RAM to return the objects which fulfil your criteria.
Heres an example of the method call to fetch.Â
[self.context executeFetchRequest:yourRequest error:&error];
As you can notice you are asking the context to look for these objects by passing an instance of NSFetchRequest and an instance of an NSError to debug incase the fetch was not successful.
This method returns an array of objects that fulfilled the criteria or nil if there were no objects.Â
Sometimes an Object may not exist but exist in your Sqlite Database, therefore the context automatically will retrieve the information from the database and create an object for you.
Thats what the Context is all about. And it should be clear now as to why its important to pass the same instance of the NSManagedObjectContext through out the classes of your app. Because you need to access the same memory space given to the Managed Object Context.Â
- Navin Dev, iOS Developer.















