I study basic data and especially work on aggregation.
The current thing I want to do: count the number of records from a table, which is in many ways inversely dependent on some criteria.
I am currently doing this:
NSExpression *ex = [NSExpression expressionForFunction:@"count:" arguments:[NSArray arrayWithObject:[NSExpression expressionForKeyPath:@"ddname"]]]; NSPredicate *pred = [NSPredicate predicateWithFormat:@"ddtype == 'Home'"]; NSExpressionDescription *ed = [[NSExpressionDescription alloc] init]; [ed setName:@"countDDEvents"]; [ed setExpression:ex]; [ed setExpressionResultType:NSInteger16AttributeType]; NSArray *properties = [NSArray arrayWithObject:ed]; NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setPredicate:pred]; [request setPropertiesToFetch:properties]; [request setResultType:NSDictionaryResultType]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"DDEvent" inManagedObjectContext:[self.currentAccount managedObjectContext]]; [request setEntity:entity]; NSArray *results = [[self.currentAccount managedObjectContext] executeFetchRequest:request error:nil]; NSDictionary *dict = [results objectAtIndex:0]; NSLog(@"Average birthdate for female heroes: %@", [dict objectForKey:@"countDDEvents"]);
Its from jeff lemarche.
EDIT : and I found my solution as
NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSPredicate *pred = [NSPredicate predicateWithFormat:@"ddtype == 'Home'"]; [request setPredicate:pred]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"DDEvent" inManagedObjectContext:[self.currentAccount managedObjectContext]]; [request setEntity:entity]; NSError *error = nil; NSUInteger count = [[self.currentAccount managedObjectContext] countForFetchRequest:request error:&error];
It works beautifully. But I want to do more queries of this type at a time. Therefore, I think this may not be the preferred way to get an invoice.
EDIT :
So, I think the approach would be appropriate.
So can anyone tell me a more efficient preferred way to do this.
Thanks.
iphone aggregation count core-data
harshalb
source share