0

I am trying to sort an array by the most common value of a property or attribute. This question and others suggest you can do this efficiently using an NSSet. However, it is merely sorting by most common string, not values of a property within custom objects. How would I get the following to return the most popular title?

NSArray<Articles*> *results = [self.managedObjectContext executeFetchRequest:fetchRequest
                                                                error:&error];

    NSCountedSet* mySet = [[NSCountedSet alloc] initWithArray:results];
    Articles* mostRead = nil;
    NSUInteger highestCount = 0;

                for(Articles* article in results) {
                    NSUInteger count = [mySet countForObject:article.title];
                    if(count > highestCount) {
                        highestCount = count;
                        mostRead = article;
                    }
                }

The above code is not returning a value as countForObject:article.title does not seem to be recognized.

user6631314
  • 1,751
  • 1
  • 13
  • 44

1 Answers1

0

Your mySet if set of Articles *. Then you count for article. title which's NSString *. Try to changes to set of NSString * should work.

 NSMutableArray<NSString *> *resultsStr = [NSMutableArray new];
 [results enumerateObjectsUsingBlock:^(Articles * _Nonnull obj,
                                      NSUInteger idx,
                                      BOOL * _Nonnull stop) {
    [resultsStr addObject:obj.title];
 }];
 NSCountedSet* mySet = [[NSCountedSet alloc] initWithArray:resultsStr];
batphonghan
  • 487
  • 3
  • 10
  • Do I still use: Articles* mostRead = nil; NSUInteger highestCount = 0; for(Articles* article in results) { NSUInteger count = [mySet countForObject:article.title]; if(count > highestCount) { highestCount = count; mostRead = article; } } – user6631314 Mar 02 '19 at 17:40