Help with Core Data in UIPickerView

So I tried many things… I would like to use the Data of a Core Data Attribute for a PickerView
I have an Entity called Task with the Attribute name. I know I need to fetch the data and I already did that, but I don’t know how to just get the values of my Attribute as an Array.

At the moment I use A UIPickerView like this:

let var1 = ["---","test","abc","xyz"]
let var2 = ["---","1","2","3","4","5","6","7"]

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return var1[row]

    return var2[row]
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return var1.count
    return var2.count
public func numberOfComponents(in pickerView: UIPickerView) -> Int{
    return 2

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
   test1 = var1[row]
    test2 = var2[row]

This is how I fetch my Data for an UITableView

    func getData() {
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    do {
        tasks = try context.fetch(Task.fetchRequest())
        print("Fetching Failed")

So I hope someone can help me noobie getting this running…

When you fetch your tasks, you get an array of NSManagedObjects (or a subclass). You can use that array to provide the info for your PickerView methods.

For example:
Instead of using var1[row], use tasks[row].value(forKeyPath: “name”) - or tasks[row].name
Instead of using var1.count, use tasks.count.

Hope that helps!

1 Like

Thank you for your answer, I got it running like at the time you wrote this :smiley:

Great minds think alike!

Have fun.

This topic was automatically closed after 166 days. New replies are no longer allowed.