Swift 3 - NSFetchRequest Distinct Results

99封情书 提交于 2019-12-05 01:27:10

The trick is to make the generic more general - instead of <BodyType> in your fetch request, use <NSFetchRequestResult>:

let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "BodyType")

The result of this fetch request is [Any], so you will need to cast to the appropriate dictionary type before using. Eg:

func getBodyTypes() {
    let context = ad.managedObjectContext
    // 1) use the more general type, NSFetchRequestResult, here:
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "BodyType")
    fetchRequest.propertiesToFetch = ["name"]
    fetchRequest.returnsDistinctResults = true
    fetchRequest.resultType = NSFetchRequestResultType.dictionaryResultType

    do {
        let results = try context.fetch(fetchRequest)

        // 2) cast the results to the expected dictionary type:
        let resultsDict = results as! [[String: String]]

        for r in resultsDict {
            bodyTypes.append(r["name"])
        }

    } catch let err as NSError {
        print(err.debugDescription)
    }
}

Note: NSFetchRequestResult is a protocol, adopted by four types:
- NSDictionary,
- NSManagedObject,
- NSManagedObjectID, and
- NSNumber

Typically, we're using it with an NSManagedObject, such as your BodyType. In this case, though, you're getting the dictionary type because of the statement:

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