Skip to content

Instantly share code, notes, and snippets.

@KanybekMomukeyev
Last active October 9, 2015 04:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KanybekMomukeyev/62f3517d289bc18daf6f to your computer and use it in GitHub Desktop.
Save KanybekMomukeyev/62f3517d289bc18daf6f to your computer and use it in GitHub Desktop.
Core data basics
Core Data Querying Basics
Jul 13, 2014
The basics of querying, filtering, sorting, and grouping persistent data in Core Data.
Retrieving Persistent Objects
// instances of the entity to fetch
NSEntityDescription *entity
= [NSEntityDescription entityForName:@"Item"
inManagedObjectContext:self.managedObjectContext];
/* `NSFetchRequest` used to query
_must_ have an `entity` set */
NSFetchRequest *request = [[NSFetchRequest alloc] init];
// set entity to fetch
request.entity = entity;
// `NSManagedObjectContext` executes queries
NSError *e = nil;
NSArray *results
= [self.managedObjectContext executeFetchRequest:request
error:&e];
if (e) {
NSLog(@"fetch error: %@", [e userInfo]);
abort();
}
// output all persistent `Item` instances
for (NSManagedObject *item in results) {
NSLog(@"item: %@", [item valueForKey:@"name"]);
}
Conditions
NSEntityDescription *entity
= [NSEntityDescription entityForName:@"Item"
inManagedObjectContext:self.managedObjectContext];
// `NSPredicate` used to filter
NSPredicate *predicate
= [NSPredicate predicateWithFormat:@"name BEGINSWITH[c] %@", @"B"];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = entity;
// set filter condition
request.predicate = predicate;
NSError *e = nil;
NSArray *results
= [self.managedObjectContext executeFetchRequest:request
error:&e];
if (e) {
NSLog(@"fetch error: %@", [e userInfo]);
abort();
}
// output `Items` having a name starting with "B" (case-insensitive)
for (NSManagedObject *item in results) {
NSLog(@"item: %@", [item valueForKey:@"name"]);
}
Sorting
NSEntityDescription *entity
= [NSEntityDescription entityForName:@"Item"
inManagedObjectContext:self.managedObjectContext];
/* `NSSortDescriptor` used to sort
needs an attribute name and direction */
NSSortDescriptor *mostRecentFirst
= [NSSortDescriptor sortDescriptorWithKey:@"createdAt"
ascending:NO];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = entity;
// set sort condition
request.sortDescriptors = @[mostRecentFirst];
NSError *e = nil;
NSArray *results
= [self.managedObjectContext executeFetchRequest:request
error:&e];
if (e) {
NSLog(@"fetch error: %@", [e userInfo]);
abort();
}
// output `Items` ordered most recent first
for (NSManagedObject *item in results) {
NSLog(@"item: %@, createdAt: %@",
[item valueForKey:@"name"],
[item valueForKey:@"createdAt"]);
}
Grouping and Aggregation
NSEntityDescription *entity
= [NSEntityDescription entityForName:@"Item"
inManagedObjectContext:self.managedObjectContext];
// attribute to group by
NSExpression *keyPath
= [NSExpression expressionForKeyPath:@"name"];
// aggregate function (count, sum, avg, min, max, etc.)
NSExpression *expression
= [NSExpression expressionForFunction:@"count:"
arguments:@[keyPath]];
/* `NSPropertyDescription` subclass used for fetching
needs a name, expression, and expression type */
NSExpressionDescription *calc
= [[NSExpressionDescription alloc] init];
calc.name = @"total";
calc.expression = expression;
calc.expressionResultType = NSInteger32AttributeType;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = entity;
// set grouping attribute
request.propertiesToGroupBy = @[@"name"];
// fetch only the group name and calculation
request.propertiesToFetch = @[@"name", calc];
// ask for dictionaries not managed objects
request.resultType = NSDictionaryResultType;
NSError *e = nil;
NSArray *results
= [self.managedObjectContext executeFetchRequest:request
error:&e];
if (e) {
NSLog(@"fetch error: %@", [e userInfo]);
abort();
}
// output each group and total
for (NSDictionary *d in results) {
NSLog(@"name: %@, total: %@", d[@"name"], d[@"total"]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment