1

I'm trying to get a distinct list of all of the values from the "flightNumber" field in my "LogLine" table. But everything I've tried has resulted in the fetch request returning the full list of flight numbers, with duplicates.

I've followed the answers from these questions:

Swift Core Data - Request with distinct results

Swift 3 - NSFetchRequest Distinct Results

But can't seem to get it to work. Here is my code:

func fetchUniqueFlightNumbers() -> [[String: Int16]]? {
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "LogLine")
    request.resultType = NSFetchRequestResultType.dictionaryResultType
    request.returnsDistinctResults = true
    request.propertiesToFetch = ["flightNumber"]

    do {
        let results = try persistenceContainer.viewContext.fetch(request) as! [[String: Int16]]
        return results
    } catch {
        print("Couldn't read flight numbers from DB \(error)")
        return nil
    }
}

The results I'm getting are:

[["flightNumber": 1], ["flightNumber": 1], ["flightNumber": 2], ["flightNumber": 2]]

I want to get the result [1,2] but I'm getting [1,1,2,2].

The attribute "flightNumber" is an Integer 16.

Is there something wrong with my code, or has something changed in Swift 4?

EDIT:

I realized that I'm only seeing this behavior in testing, when my persistent store is configured as an NSInMemoryStoreType. So it isn't as much of a problem, I'll just have to rethink the unit tests for this part of the code. I am curious why I'm seeing this difference in behavior between the two store types though.

Chris.B
  • 493
  • 1
  • 5
  • 16

1 Answers1

0

@Chris.B I see your post is a bit old but unsolved. I just went through a similar problem but using FethchedResultControllerand I found out a lot. The problem you're having is that you're not using .propertiesToGroupBy and this is the properties you want distinct results of. It is a mandatory NSFetchRequest property and must be used in order to get distinct results. For a complete insight check my answer at my own question as is a very detailed sort of step-by-step guide. Removing duplicate objects from fetch based on object parameter UPDATED Swift Hope it helps.

Vincenzo
  • 5,304
  • 5
  • 38
  • 96