Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Core Data - Request with distinct results

how I can call es request with distinct values in swift?

This is my code:

let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    let context: NSManagedObjectContext = appDelegate.managedObjectContext

    let request = NSFetchRequest(entityName: "MedicalData")
    request.propertiesToFetch = NSArray(object: "docID")
    request.returnsObjectsAsFaults = false
    request.returnsDistinctResults = true

    var results:NSArray = context.executeFetchRequest(request, error: nil)

    for data in results {
        var thisData = data as MedicalData
        println(thisData.docID)
    }

I want to get distinct values for "docID" but I get all of the entity :(

Thank your for help!

like image 878
Maxim Avatar asked Jun 26 '14 14:06

Maxim


2 Answers

You need to set

request.resultType = NSFetchRequestResultType.DictionaryResultType

It returns dictionaries, but the distinct filter should work.

If you do not want to go down that route, filter in memory (also recommended). Do a normal fetch and then

let distinct = NSSet(array: results.valueForKeyPath("docID") as [String])

With Swift 2.0 I prefer

let distinct = NSSet(array: results.map { $0.docID })
like image 197
Mundi Avatar answered Oct 13 '22 12:10

Mundi


As already mentioned the key is using

fetchRequest.resultType = NSFetchRequestResultType.DictionaryResultType

and

fetchRequest.propertiesToFetch = ["propertyName"]

both are required for distinct to work

fetchRequest.returnsDistinctResults = true

The next step is to deal with the results as Swift Dictionaries and returning the wanted values.

let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    let managedContext = appDelegate.managedObjectContext!
    //FetchRequest
    let fetchRequest = NSFetchRequest(entityName: "Purchase")
    fetchRequest.propertiesToFetch = ["year"]
    fetchRequest.resultType = NSFetchRequestResultType.DictionaryResultType
    fetchRequest.returnsDistinctResults = true
    //Fetch
    var error: NSError?
    if let results = managedContext.executeFetchRequest(fetchRequest, error: &error)  {
        var stringResultsArray: [String] = []
        for var i = 0; i < results.count; i++ {
            if let dic = (results[i] as? [String : String]){
                if let yearString = dic["year"]?{
                    stringResultsArray.append(yearString)
                }
            }
        }
        return stringResultsArray
    }else {
        println("fetch failed: \(error?.localizedDescription)")
    }
    return []
like image 29
Yedy Avatar answered Oct 13 '22 13:10

Yedy