Swift Core Data - Request with distinct results

前端 未结 3 1120
天涯浪人
天涯浪人 2021-01-03 03:08

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

This is my code:

let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate a         


        
3条回答
  •  渐次进展
    2021-01-03 03:24

    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 []
    

提交回复
热议问题