Search code examples
iosobjective-ccore-datanspredicatensfetchrequest

IOS Core Data : Count Duplicated values


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;
@end

How to get the most popular artistName using a NSFetchRequest (and without NSCounterSet)?


Solution

  • You do it by

    • Grouping the results by artistName, and
    • 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];
    [countExprDesc setName:@"count"];
    [countExprDesc setExpression:countExpr];
    [countExprDesc setExpressionResultType:NSInteger64AttributeType];
    

    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];
    [fr setPropertiesToGroupBy:@["artistName"];
    [fr setResultType:NSDictionaryResultType];
    

    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.