1

In Core Data, I have a large number of "City" objects, each of which has a "country" property.

Rather than have a very long scrollable list of cities, I need to have a separate screen which lists just Countries in a UITableView. The user then selects a country and is taken to a new screen, which has the Cities for that Country.

Note: This is for a game, so the UITableView data source is bound to a SKScene, but I don't think that should make any difference as it works fine for other screens.

I have figured out the detail screen which displays the Cities for a specific country and it works fine in test with hard-coded data.

I am using Swift 5 so my data calls are like this:

let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "City")
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
fetchRequest.predicate = NSPredicate(format: "country = %@", country)
try fetchedResultsController.performFetch()

However for the other screen, I don't know how to "group" the Countries, which are the property on each City, and make the groupings the data source for the UITableView on the other screen.

a) I could create an array of Countries, but how would I have the fetchedResultsController return the Country data to UITableView?

b) Or, is it possible to group or filter objects within a fetchedResultsController?

c) Or, is it possible to do SQL-like grouping within a fetch request?

Thanks

Jon Winstanley
  • 23,010
  • 22
  • 73
  • 116
  • https://developer.apple.com/documentation/coredata/nsfetchrequest/1506191-propertiestogroupby ? – Larme Dec 28 '20 at 14:27
  • check https://stackoverflow.com/questions/7000768/coredata-get-distinct-values-of-attribute – CSmith Dec 28 '20 at 14:32

1 Answers1

0

Thanks @Larme for the link to https://developer.apple.com/documentation/coredata/nsfetchrequest/1506191-propertiestogroupby

So to get this working, Results Container needs to be defined with NSDictionary.

var fetchedResultsController: NSFetchedResultsController<NSDictionary>!

The fetchRequest needs to be set to group and fetch the specific property.

fetchRequest.propertiesToFetch = ["country"]
fetchRequest.propertiesToGroupBy = ["country"]
fetchRequest.resultType = .dictionaryResultType

Then in the methods where we need to access the data:

// cell data
let countryName = (fetchedResultsController.object(at: indexPath) as NSDictionary)["country"]!
cell.textLabel?.text = "\(countryName)"

Thanks for pointing me in the right direction!

Jon Winstanley
  • 23,010
  • 22
  • 73
  • 116