How would I do the equivalent of this statement in Core Data? Basically I want to get a list of the 10 most occurrences of foo along w/ how many times it occurs.
Basically I’m recording all of my users searches as individual entries in Core Data. I want to be able to select their 10 most searched items and display them in order starting w/ the most popular. So basically I want something like:
- Baa | 10
- Sea | 8
- Box | 6
etc…..
Thanks for any help you can provide. I’m still new to Core Data.
SELECT foo,
COUNT(foo) AS occurances
FROM bar
GROUP BY foo
ORDER BY occurances DESC
LIMIT 10;
First, create a Core Data Entity that has: userSearchTerm and userSearchDate. And create a record everytime a search is done.
Start the code by declaring the fetch request.
And use
NSPredicateto filter by date:The [cd] in the like filter specifies it’s not case-sensitive. You may also need to change this filter depending on the date and format you want to use
Then, set the fetchResultType as
NSDictionaryResultType:This will return a dictionary which you can use.
To use aggregate functions you need to use
NSExpressionDescriptionThis is an extensive code and I’m not able to test it correctly for you, but you can read it here. On section Fetching Specific Values, it describes how to do the aggregate functions:
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/CoreData/Articles/cdFetching.html
For a reference of all the available aggregate functions for
NSExpressiongo to function expressionForFunction:arguments: where the list is located.