trovo questo metodo (più o meno simile alla risposta accettata) di essere un po' più pulito e più facile capire. Questo è l'SQL equivalente a:
SELECT COUNT(*), a_value FROM my_table GROUP BY a_value;
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:[MyTable className]];
// create expression for grouped column
NSExpressionDescription *aValueDescription = [[NSExpressionDescription alloc] init];
aValueDescription.name = @"aValue"; // name of key in result dictionary
aValueDescription.expression = [NSExpression expressionWithFormat:@"aValue"];
aValueDescription.expressionResultType = NSObjectIDAttributeType;
// create expression for count
NSExpressionDescription *countDescription = [[NSExpressionDescription alloc] init];
countDescription.name = @"count"; // name of dictionary key in result dictionary
countDescription.expression = [NSExpression expressionWithFormat:@"[email protected]"];
countDescription.expressionResultType = NSInteger32AttributeType;
// fill out fetch request
fetchRequest.propertiesToGroupBy = @[@"aValue"];
fetchRequest.propertiesToFetch = @[aValueDescription, countDescription];
//fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"count" ascending:NO]]; // not sure why this crashes
fetchRequest.resultType = NSDictionaryResultType; // required for "group by" requests
NSError *error = nil;
NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
La restituito results
è un array di NSDictionary. Nota che la descrizione delle proprietà name
può essere qualsiasi cosa tu voglia: sono solo i nomi delle chiavi nei dizionari restituiti. Si può aggiungere un predicato alla richiesta di recupero per filtrare le righe dalla tabella; questo codice restituisce tutte le righe.
punti bonus a chi mi può dire come fare il lavoro descrittore di sorta ...
Fateci sapere se una risposta che ha aiutato. –