1

i want to get distinct dates from core data. with this code fetchRequest.returnsDistinctResults = true is not working. it is still showing all values.

guard let appDelegate =
          UIApplication.shared.delegate as? AppDelegate else {
            return
        }
    
    let managedContext = appDelegate.persistentContainer.viewContext
    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Journal")
    
    
    fetchRequest.propertiesToFetch = ["dateAsNumber"]
    fetchRequest.returnsDistinctResults = true

    do {
    
        dateListSquare = try managedContext.fetch(fetchRequest)
        
    } catch let error as NSError {
      
        print("Could not fetch. \(error), \(error.userInfo)")
    }
  • Give a look for this answer: https://stackoverflow.com/a/60101960/9732124 from Johannes Fahrenkrug – cagy Oct 07 '20 at 07:30
  • Does this answer your question? [CoreData get distinct values of Attribute](https://stackoverflow.com/questions/7000768/coredata-get-distinct-values-of-attribute) – gcharita Oct 07 '20 at 08:28

1 Answers1

4

If you want distinct results, you need to set the fetch request's result type to NSFetchRequestResultType.dictionaryResultType. You can't fetch managed objects and get distinct results, since there might be more than one managed object with the same value.

That would look something like

let fetchRequest: NSFetchRequest<NSDictionary> = NSFetchRequest(entityName: "Journal")
fetchRequest.propertiesToFetch = ["dateAsNumber"]
fetchRequest.returnsDistinctResults = true
fetchRequest.resultType = .dictionaryResultType

The result will be an array of dictionaries. Each will have one key per entry in propertiesToFetch (just one in this case).

If you use propertiesToFetch without dictionaryResultType, you affect how faulting works but not the contents of the result. Using returnsDistinctResults only works if you also use propertiesToFetch, so it's also affected by whether you use dictionaryResultType.

Tom Harrington
  • 69,312
  • 10
  • 146
  • 170