I have a lot of saved Objects "Tracks" in my app as :
@interface Track : NSManagedObject
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *artistName;
How to get the most popular artistName using a NSFetchRequest (and without NSCounterSet)?
Best How To :
You do it by
- Grouping the results by
- Creating an
NSExpression that counts the number of occurrences of
artistName in those grouped results.
First create the expression, naming it
count, using the
count function, and returning an integer result:
NSExpression *countExpr = [NSExpression expressionWithFormat:@"count:(artistName)"];
NSExpressionDescription *countExprDesc = [[NSExpressionDescription alloc] init];
Then create the fetch request to use this, both fetching and grouping by the expression value:
NSFetchRequest *fr = [[NSFetchRequest alloc] initWithEntityName:@"Track"];
[fr setPropertiesToFetch:@[@"artistName", countExprDesc];
When you execute the fetch, you'll get back an array of dictionaries. Each dictionary will have two keys:
artistName will be values of your
artistName property, and
count will be the number of times each artist name appears.
You'll need to find the max value in that array yourself, because unfortunately you can't tell fetch requests to sort results by expression values.