Wednesday 11 July 2012

Core Data Brief introduction

What's the Core Data?

Suppose you have the object named "People", it has two variables: name which is the string type, age which is the int type.

class People
{
      public string name;
      public int age;
}

Now I want to these people to persistent, so I use a "place" to store my people.
 No matter which will do these steps:

1.  define the people class.
2.  make one "place" to store it. (xml, binary, sqlite as you like)
3.  make the relation the data from the file with the people class. It can help you map the data to people, and map the people to data.

and so on.....

For the developer, maybe you only care the object, which you can delete, create, update, you don't care how it persistence, the style of it store, how it map to you object...
you only want to change the object, it auto changes in the persistence, you create the object, it auto insert the data in the persistence, you delete the object, it auto delete the data in persistence.

So the Core data help you.
Core Data describes data with a high level data model expressed in terms of entities and their relationships plus fetch request that retrieve entities meeting specific criteria.
Code can retrieve and manipulate this data on a purely object level without having to worry about the details of storage and retrieval.




Let's use this.
1.
First we will create the Data Model to store our "object"





 Choose the Data Model, and name it as you like.


2.
Then we will has the *.xcdatamodel in our project, its home of our object.




And it has three components:  ENTITIES, FETCH REQUESTS, CONFIGURATIONS.

The ENTITY is model that mapped our purely object.
So let add our variable to the Entity. First Add the Entity,Find the Add Entity at the bottom left of the window and click it. A new Entity will appear in the list of entities in the lefthand table, change its name.

 Then you click + button in the Attribute section and edit the Attribute and Type values:




Then we finish the persistence of our data, now we should make our object to connect to these entity. We used the NSManagedObject to do this.



Now we can finish our preparatory work. we want to use these object, we must follow Core Data stack.


Don't be afraid!
Let me show what stack do.

First: We must find our entity. Yep, it's in the file (*.xcdatamodel file that created).
So we use the Managed Object Model.

A managed object model that describes the entities in the stores.

NSManagedObjectModel * managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];

Then: There is another component to connect your object to the persistence data, this is the Persistent Store Coordinator.

A persistent store coordinator that aggregates all the stores, and context used it to persistence the object graph, and retrieve the entity information.



 NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];

it initializes with model, it must know the entity you want to store and the entity's information.

Next: We will find a place to store your entity by your type. so you must tell persistent object store coordinator, you have a store.

A persistent object store that maps between records in the store and objects in your application.

    NSString *path = [self storePath];
    NSURL *storeURL = [NSURL fileURLWithPath:path];
   
    NSError *error = nil;
   
    if (![psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        [NSException raise:@"Open failed" format:@"Reason: %@", [error localizedDescription]];
    }

We give a path to store our entity, and the type for our persistence.


Final:  We must use something to manipulate our object,  to connect with the coordinator.
A managed object context that provides a scratch pad for managed objects. 

    NSManagedObejctContext* context = [[NSManagedObjectContext alloc] init];
    [context setPersistentStoreCoordinator:psc];


We general communicate with NSManagedObjectContext.
We can Insert the New entity to the store.

    People *e = [NSEntityDescription insertNewObjectForEntityForName:@"People" inManagedObjectContext:context];
   
    NSError *error = nil;
    [context save:&error];

query the entity in the store

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"People" inManagedObjectContext:[self managedObjectContext]];
[fetchRequest setEntity:entity];
 
 NSError *error = nil;
NSMutableArray *mutableFetchResults = [[self.managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy];
if (mutableFetchResults == nil) 
}
 

delete the entity in the store
 
NSManagedObject *eventToDelete = [eventsArray objectAtIndex:indexPath.row]; 
[managedObjectContext deleteObject:eventToDelete]; 
 
 
 We can get More information from apple website, I just make a brief introducation.
 Hope you like. 
 
 Reference Link:
 
 wiki: http://en.wikipedia.org/wiki/Core_Data 

 apple: http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/CoreData/cdProgrammingGuide.html