Created
May 1, 2013 17:20
-
-
Save darcyliu/5496717 to your computer and use it in GitHub Desktop.
Core Data Snippets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//1 Creating a New Managed Object Context | |
//To create a new managed object context, you need a persistent store coordinator. | |
NSPersistentStoreCoordinator *psc = <#Get the coordinator#>; | |
NSManagedObjectContext *newContext = [[NSManagedObjectContext alloc] init]; | |
[newContext setPersistentStoreCoordinator:psc]; | |
//using the same coordinator as the existing one | |
NSManagedObjectContext *context = <#Get the context#>; | |
NSPersistentStoreCoordinator *psc = [context persistentStoreCoordinator]; | |
NSManagedObjectContext *newContext = [[NSManagedObjectContext alloc] init]; | |
[newContext setPersistentStoreCoordinator:psc]; | |
//2 Getting the Managed Object Model and Entities | |
NSManagedObjectContext *context = <#Get the context#>; | |
NSPersistentStoreCoordinator *psc = [context persistentStoreCoordinator]; | |
NSManagedObjectModel *model = [psc managedObjectModel]; | |
NSEntityDescription *entity = [[model entitiesByName] objectForKey:@"<#Entity name#>"]; | |
//3 Adding a Persistent Store | |
NSPersistentStoreCoordinator *psc = <#Get the coordinator#>; | |
NSURL *storeUrl = [NSURL fileURLWithPath:@"<#Path to store#>"]; | |
NSString *storeType = <#Store type#>; // A store type, such as NSSQLiteStoreType | |
NSError *error; | |
if (![psc addPersistentStoreWithType:storeType configuration:nil | |
URL:storeUrl options:nil error:&error]) { | |
// Handle the error. | |
} | |
//4 Basic Fetch | |
NSManagedObjectContext *context = <#Get the context#>; | |
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; | |
NSEntityDescription *entity = [NSEntityDescription entityForName:@"<#Entity name#>" | |
inManagedObjectContext:context]; | |
[fetchRequest setEntity:entity]; | |
NSError *error; | |
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error]; | |
if (fetchedObjects == nil) { | |
// Handle the error. | |
} | |
//5 Fetch with Sorting | |
NSManagedObjectContext *context = <#Get the context#>; | |
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; | |
NSEntityDescription *entity = [NSEntityDescription entityForName:@"<#Entity name#>" | |
inManagedObjectContext:context]; | |
[fetchRequest setEntity:entity]; | |
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"<#Sort key#>" | |
ascending:YES]; | |
NSArray *sortDescriptors = @[sortDescriptor]; | |
[fetchRequest setSortDescriptors:sortDescriptors]; | |
NSError *error; | |
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error]; | |
if (fetchedObjects == nil) { | |
// Handle the error. | |
} | |
//6 Fetch with a Predicate | |
NSManagedObjectContext *context = <#Get the context#>; | |
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; | |
NSEntityDescription *entity = [NSEntityDescription entityForName:@"<#Entity name#>" | |
inManagedObjectContext:context]; | |
[fetchRequest setEntity:entity]; | |
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"<#Predicate string#>", | |
<#Predicate arguments#>]; | |
[fetchRequest setPredicate:predicate]; | |
NSError *error; | |
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error]; | |
if (fetchedObjects == nil) { | |
// Handle the error. | |
} | |
//7 Fetch with a Predicate Template | |
// Assume an instance variable: | |
// NSPredicate *predicateTemplate; | |
- (NSPredicate *)predicateTemplate { | |
if (predicateTemplate == nil) { | |
predicateTemplate = [NSPredicate predicateWithFormat:@"<#Key#> <#Operator#> <#$Variable#>"]; | |
} | |
return predicateTemplate; | |
} | |
// use predicateTemplate | |
NSManagedObjectContext *context = <#Get the context#>; | |
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; | |
NSEntityDescription *entity = [NSEntityDescription entityForName:@"<#Entity name#>" | |
inManagedObjectContext:context]; | |
[fetchRequest setEntity:entity]; | |
NSDictionary *variables = @{ @"<#Variable#>" : <#Value#> }; | |
NSPredicate *predicate = [[self predicateTemplate] | |
predicateWithSubstitutionVariables:variables]; | |
[fetchRequest setPredicate:predicate]; | |
NSError *error; | |
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error]; | |
if (fetchedObjects == nil) { | |
// Handle the error. | |
} | |
//8 Fetch with Sorting and a Predicate | |
NSManagedObjectContext *context = <#Get the context#>; | |
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; | |
NSEntityDescription *entity = [NSEntityDescription entityForName:@"<#Entity name#>" inManagedObjectContext:context]; | |
[fetchRequest setEntity:entity]; | |
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"<#Sort key#>" ascending:YES]; | |
NSArray *sortDescriptors = @[sortDescriptor]; | |
[fetchRequest setSortDescriptors:sortDescriptors]; | |
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"<#Predicate string#>", | |
<#Predicate arguments#>]; | |
[fetchRequest setPredicate:predicate]; | |
NSError *error; | |
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error]; | |
if (fetchedObjects == nil) { | |
// Handle the error. | |
} | |
//9 Fetching Distinct Values | |
NSManagedObjectContext *context = <#Get the context#>; | |
NSEntityDescription *entity = [NSEntityDescription entityForName:@"<#Entity name#>" inManagedObjectContext:context]; | |
NSFetchRequest *request = [[NSFetchRequest alloc] init]; | |
[request setEntity:entity]; | |
[request setResultType:NSDictionaryResultType]; | |
[request setReturnsDistinctResults:YES]; | |
[request setPropertiesToFetch:@[@"<#Attribute name#>"]]; | |
// Execute the fetch. | |
NSError *error; | |
id requestedValue = nil; | |
NSArray *objects = [context executeFetchRequest:request error:&error]; | |
if (objects == nil) { | |
// Handle the error. | |
} | |
//10 Fetching Attribute Values that Satisfy a Given Function | |
NSManagedObjectContext *context = <#Get the context#>; | |
NSFetchRequest *request = [[NSFetchRequest alloc] init]; | |
NSEntityDescription *entity = [NSEntityDescription entityForName:@"<#Entity name#>" inManagedObjectContext:context]; | |
[request setEntity:entity]; | |
// Specify that the request should return dictionaries. | |
[request setResultType:NSDictionaryResultType]; | |
// Create an expression for the key path. | |
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"<#Key-path for the property#>"]; | |
// Create an expression to represent the function you want to apply | |
NSExpression *expression = [NSExpression expressionForFunction:@"<#Function name#>" | |
arguments:@[keyPathExpression]]; | |
// Create an expression description using the minExpression and returning a date. | |
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init]; | |
// The name is the key that will be used in the dictionary for the return value. | |
[expressionDescription setName:@"<#Dictionary key#>"]; | |
[expressionDescription setExpression:expression]; | |
[expressionDescription setExpressionResultType:<#Result type#>]; // For example, NSDateAttributeType | |
// Set the request's properties to fetch just the property represented by the expressions. | |
[request setPropertiesToFetch:@[expressionDescription]]; | |
// Execute the fetch. | |
NSError *error; | |
id requestedValue = nil; | |
NSArray *objects = [context executeFetchRequest:request error:&error]; | |
if (objects == nil) { | |
// Handle the error. | |
} | |
else { | |
if ([objects count] > 0) { | |
requestedValue = [[objects objectAtIndex:0] valueForKey:@"<#Dictionary key#>"]; | |
} | |
} | |
//11 Creating a Managed Object | |
NSManagedObjectContext *context = <#Get the context#>; | |
<#Managed Object Class#> *newObject = [NSEntityDescription | |
insertNewObjectForEntityForName:@"<#Entity name#>" | |
inManagedObjectContext:context]; | |
//12 Saving a Managed Object | |
NSManagedObjectContext *context = <#Get the context#>; | |
NSError *error; | |
if (![context save:&error]) { | |
// Handle the error. | |
} | |
//13 Deleting a Managed Object | |
NSManagedObject *aManagedObject = <#Get the managed object#>; | |
NSManagedObjectContext *context = [aManagedObject managedObjectContext]; | |
[context deleteObject:aManagedObject]; | |
NSError *error; | |
if (![context save:&error]) { | |
// Handle the error. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment