Swift Core Data - Request with distinct results

馋奶兔 提交于 2019-11-30 15:40:10

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 })

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

NSPredicate will allow you to search for specific values and retrieve only the data you need from core data:

  var StoredResults = [NSManagedObject]()

  func fetchRequest(docID : String ){

        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let managedContext = appDelegate.managedObjectContext
        let request = NSFetchRequest(entityName: "EntityContainingDocID")

        let predicate =  NSPredicate(format:"docID == %@", docID)
        request.predicate = predicate

    do {
        let results =
        try managedContext.executeFetchRequest(request)

        StoredResults = results as! [NSManagedObject]

        } catch let error as NSError {
              print(" error executing fetchrequest  ", error)
        }
    }

In this example we are only looking to return specific values matching a string in the "docID" column but NSPredicate is a handy way of building SQL-like queries into your code and is pretty flexible.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!