Core Data


* NSManagedObjectModel
	+ NSEntityDescription
		+ NSAttributeDescription
		+ NSRelationshipDescription

* NSManagedObjectContext
	+ NSManagedObject
	+ NSPersistentStoreCoordinator
		+ NSPersistentStore
		+ NSManagedObjectModel


Cách tạo 1 NSPersistentStoreCoordinator

```objectivec
//Thiết lập nơi lưu database
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"OrgChart.sqlite"]; 


//Tạo 1 PersistentStoreCoordinator
NSError *error = nil;
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

//Thiết lập loại Store là SQLite
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
{
//Trường hợp lỗi 
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort(); 
}
```

## Thiết lập request

* NSFetchRequest
	* NSPredicate : Các điều kiện truy vấn
		* NSComparisonPredicate
		* NSCompoundPredicate
	* NSSortDescriptor : Cách sắp xếp
	* NSExpression: Biểu thức chính quy

## Insert data
```objectivec
//1-Tạo ManageObject cho Entity
NSManagedObject *newPerson = [NSEntityDescription insertNewObjectForEntityForName:@"Person"? inManagedObjectContext:self.managedObjectContext];

//2-Set thông tin cho ManageObject

[newPerson setValue:@"John" forKey:@"name"];
[newPerson setValue:[NSNumber numberWithInt:[@"John" hash]] forKey:@"id"];

//3- Thực hiện save context
NSError *savingError = nil;
if ([self.managedObjectContext save:&savingError])
{ 
NSLog(@"Successfully saved the context.");
} else 
{
NSLog(@"Failed to save the context. Error = %@", savingError);
}
```

# Get DATA
```objectivec
- (void)readData {
//1- Lấy context
NSManagedObjectContext *context = [self managedObjectContext];

//2-Tạo EntityDescription
NSEntityDescription *orgEntity = [NSEntityDescription entityForName:@"Organization"? inManagedObjectContext:context];

//3- Tạo FetchRequest

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 

//4- Set Entity cho FetchRequest
[fetchRequest setEntity:orgEntity];

//5- Excute FetchRequest
NSArray *organizations = [context executeFetchRequest:fetchRequest error:nil];
id organization;

//6-Loop lấy Thông tin
NSEnumerator *it = [organizations objectEnumerator]; 
while ((organization = [it nextObject]) != nil)
{
	NSLog(@"Organization: %@", [organization valueForKey:@"name"]);
￼￼NSManagedObject *leader = [organization valueForKey:@"leader"];
[self displayPerson:leader withIndentation:@" "]; 
}
}

- (void)displayPerson:(NSManagedObject*)person withIndentation:(NSString*)indentation {
NSLog(@"%@Name: %@", indentation, [person valueForKey:@"name"]);
// Increase the indentation for sub-levels
indentation = [NSString stringWithFormat:@"%@ ", indentation];
NSSet *employees = [person valueForKey:@"employees"]; id employee;
NSEnumerator *it = [employees objectEnumerator]; while ((employee = [it nextObject]) != nil)
{
[self displayPerson:employee withIndentation:indentation];
} }

```

Delete Data

```objectivec
/* Create the fetch request first */
//1- Tạo Fetch request

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

/* Here is the entity whose contents we want to read */
//2- Chỉ định Entity 
NSEntityDescription *entity =
[NSEntityDescription entityForName:@"Person"
inManagedObjectContext:self.managedObjectContext];

/* Tell the request that we want to read the contents of the Person entity */
//3- Chỉ định cho Entity cho Request.

[fetchRequest setEntity:entity]; NSError *requestError = nil;


//4-Thực thi request
/* And execute the fetch request on the context */
NSArray *persons =
[self.managedObjectContext executeFetchRequest:fetchRequest
error:&requestError];

/* Make sure we get the array */

 if ([persons count] > 0){
/* Delete the last person in the array */

//5-Chỉ định Object cần DELETE
   Person *lastPerson = [persons lastObject];
[self.managedObjectContext deleteObject:lastPerson];

//6- Kiểm tra object được DELETE thành công không
if ([lastPerson isDeleted]){
NSLog(@"Successfully deleted the last person...");
NSError *savingError = nil;


//7- SAVE Context
if ([self.managedObjectContext save:&savingError]){
NSLog(@"Successfully saved the context."); } else {
NSLog(@"Failed to save the context."); }
} else {
NSLog(@"Failed to delete the last person.");
}
} else {
NSLog(@"Could not find any Person entities in the context.");
}
```


##SẮP XẾP DATA

```objectivec
//1- Tạo các đối tượng cần sort
NSSortDescriptor *ageSort = [[NSSortDescriptor alloc] initWithKey:@"age"
ascending:YES];
NSSortDescriptor *firstNameSort = [[NSSortDescriptor alloc] initWithKey:@"firstName"
ascending:YES];


//2- Tạo mảng cần sort
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects: ageSort,
firstNameSort, nil]; 

//3-Set Sort cho Request
fetchRequest.sortDescriptors = sortDescriptors;
```

## TẠO 1 truy vấn điều kiện

 ```objectivec
//1- Tạo 1 truy vấn
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains %@", @"Inc."];
 [fetchRequest setPredicate:predicate];

//2- Tạo đối tượng sort
NSSortDescriptor *sortByName = [[NSSortDescriptor alloc] initWithKey:@"name"? ascending:YES];


//3- Thiết lập thuộc tính cho Request
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortByName]];
 ```