在Core Data中获取唯一的Attribute / Column值

时间:2017-08-18 12:53:17

标签: ios swift xcode core-data swift3

我有一个Entity CalculatorProduct 属性为' id','品牌','类别',' mrp' 我想仅提取'类别'列/属性

  let context = DataBaseController.getContext()
    let fetchRequest:NSFetchRequest<CalculatorProduct> = CalculatorProduct.fetchRequest()

    fetchRequest.propertiesToFetch = ["category"]

    fetchRequest.returnsDistinctResults = true
    do{

        let result = try context.fetch(fetchRequest)


        print("array from db \(String(describing: result.count))")
        print("array from db \(String(describing: result))")

        for val in result{

            print("\(String(describing: val.category))")
        }

    }
    catch{

        print("error in fetching is\(error)")
    }

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

let context = DataBaseController.getContext()
let fetchRequest:NSFetchRequest<CalculatorProduct> = CalculatorProduct.fetchRequest()
fetchRequest.propertiesToFetch = ["category"]
fetchRequest.returnsDistinctResults = true
fetchRequest.resultType = .dictionaryResultType
do {
    let result = try context.fetch(fetchRequest) as! [[String:Any]]

    print("array from db \(String(describing: result.count))")
    print("array from db \(String(describing: result))")

    for val in result{
        print("\(String(describing: val["category"]))")
    }
}
catch{
    print("error in fetching is\(error)")
}