I try to set up an NSFetchRequest
for an entity Location
with properties like country
and city
:
country | city
————————————————
Germany | Berlin
USA | San Francisco
USA | New York
Germany | Munich
Germany | Munich
USA | San Francisco
Germany | Stuttgart
The NSFetchRequest
should return the country (or a Location object with the appropriate country) and the number of cities.
[
{ country: 'Germany', cityCount: 3 },
{ country: 'USA', cityCount: 2 }
]
I know that I can just fetch all entries and 'count it myself' but I am interested in how to set up an appropriate fetch request (or if it's possible to do so) and would like to see how you would do it! :)
The correct answer to this question to refactor the data model in order to avoid redundancy.
The country strings are repeated unnecessarily in the table. Additionally, you make a simple query gratuitously complicated. The model should reflect your data, and writing out "USA" for every American city is just not smart or efficient.
Your data model should look like this
Country <----->> City
Now you can just fetch all countries and get the cities with cities.count
.