0

How could I fetch distinct values from core data to be shown in UIPicker ?

I've the following code. It works fine but shows duplicate content :

    func CD_Fetch_Value_Database() {
        let context = getcontext()

        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Calculation")
        fetchRequest.predicate = NSPredicate(format: "test= %@", cd_test)

        fetchRequest.returnsObjectsAsFaults = false
        fetchRequest.returnsDistinctResults = true

    do {
        Value_Database = try context.fetch(fetchRequest) as! [Calculation]


    } catch let error as NSError {
        let errorDialog = UIAlertController(title: "Error!", message: "Failed to save! \(error): \(error.userInfo)", preferredStyle: .alert)
        errorDialog.addAction(UIAlertAction(title: "Cancel", style: .cancel))
        present(errorDialog, animated: true)
    }
}

Thank you!

JosWico
  • 1
  • 2
  • This is pretty much the same question as: https://stackoverflow.com/questions/34161786/reduce-array-to-set-in-swift – ozzieozumo Apr 24 '18 at 14:30
  • You just want to use map on your [Calculation] to get an array of values (e.g. the title or whatever), and then use the convenience init of Set to create a Set which will have no duplicates by definition. – ozzieozumo Apr 24 '18 at 14:31
  • Unrelated: Idiomatic styling for Swift is camelcasing. Starting a function name with a capital letter (horse case) is a no-no, as is using underscores (snake case). That function should be renamed to something like `fetchValueFromDatabase()`. There's really no need to pseudo-namespace the method with "CD" – jakehawken Apr 24 '18 at 19:22
  • 1
    @jakehawken Thank you, I'll keep this in mind. I'm still learning swift – JosWico Apr 26 '18 at 14:34

1 Answers1

0

You haven’t provided enough information to get distinct results. “Distinct” here depends on which properties should have distinct values. They don’t all have to be distinct unless you want that. The documentation for returnsDistinctResults says that

This value is used only if a value has been set for propertiesToFetch.

So, that’s your next step.

Tom Harrington
  • 69,312
  • 10
  • 146
  • 170
  • Okay, I guess I have to add following line: "fetchRequest.propertiesToFetch = ["name"]" This still causes an error (Could not cast value of type 'NSKnownKeysDictionary1' (0x1100ebfe8) to 'MyApp.Calculation' (0x10e4e2600).)Sorry but I'm a swift beginner ... Could you provide me a sample code for above mentioned example, please? – JosWico Apr 26 '18 at 14:25