Swift Core Data获取数据1列

时间:2018-09-16 09:19:22

标签: swift core-data

我无法通过“名称”列获取数据。响应后,系统会在“人员”中打印所有属性。帮帮我,谢谢。

 private func getPeople(product: String) {
        let temp = product
        let entityDescription = NSEntityDescription.entity(forEntityName: "People", in: context)
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>()
        fetchRequest.entity = entityDescription
        fetchRequest.includesPropertyValues = true
        fetchRequest.returnsObjectsAsFaults = false
        fetchRequest.predicate = NSPredicate(format: "product == %@", temp)
        fetchRequest.propertiesToFetch = ["name"]
        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)]
        do {
            let personList = try context.fetch(fetchRequest) as! [People]

            print(personList)
        } catch let error as NSError {
            print(error)
        }
    }

1 个答案:

答案 0 :(得分:0)

要仅获取特定属性,请求的resultType必须为dictionaryResultType

private func getPeople(product: String) {

        let fetchRequest = NSFetchRequest<NSDictionary>(entityName: "People")
        fetchRequest.predicate = NSPredicate(format: "product == %@", product)
        fetchRequest.resultType = .dictionaryResultType
        fetchRequest.propertiesToFetch = ["name"]
        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)]
        do {
            let personList = try context.fetch(fetchRequest) as! [[String:String]]

            print(personList)
        } catch {
            print(error)
        }
    }
}