0

Suppose I have Person entity with properties: id, name, age:

And I have following records:

101, Katherine, 23
102, Madelaine, 23
103, Katherine, 27
104, Vicky, 18
105, Kirsten, 45
106, Vicky, 12

And I need all records sorted by age, without duplicating name.

The output should be:

105, Kirsten, 45
103, Katherine, 27
102, Madelaine, 23
104, Vicky, 18

This is how I create NSFRC:

    let context = NSManagedObjectContext.mr_default()
    let fetchRequest = NSFetchRequest<Person>(entityName: "Person")
    let ageDescriptor = NSSortDescriptor(key: "age", ascending: false)

    fetchRequest.sortDescriptors = [ageDescriptor]

    fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
    fetchedResultsController.delegate = self

How to apply rule to fetch all persons and only one (oldest) person with the same name?

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358

1 Answers1

0

You can use the property returnsDistinctResults and propertiesToFetchin NSFetchrequest to return only distinct results of a fetch request. In your case the propertiesToFetch will be the name of the entity.

You can find more info here: https://developer.apple.com/documentation/coredata/nsfetchrequest

Just as example code. (I am doing it off top of my head so may not be 100% accurate with exact syntax):

let entity = NSEntityDescription.entity(forEntityName: "Person", in: context)

let entityProperties = entity.propertiesByName
let namePropertyDescription = entityProperties["name"]

fetchrequest.propertiesToFetch = [namePropertyDescription]
fetchrequest.returnsDistinctResults = true
AdiTheExplorer
  • 259
  • 4
  • 13