Search code examples
uitableviewcore-dataswift3uistepper

how to load UIStepper value from Coredata?


I use CoreData in my project and I have uitableview and in every cell I have UIStepper. Now I can save UIStepper value in CoreData, For example when I click on + it's work fine and save the new value in the CoreDate and when I restart my App I can see my last uistepper value but when I click + it will star count from 1 , not from the last value I have and it will save the new value in the CoreData.

how I can load the last value from the core data and make my UIStepper start counting from this value (last value in core data)

my function

func stepper2 (sender: UIStepper){
        let appD = UIApplication.shared.delegate as! AppDelegate
        let context = appD.persistentContainer.viewContext


        //save the object
        let aa = Tasks[sender.tag]

        aa.stepper = (sender.value)


        do {
            try context.save()
            print("updated!")
            print (aa)
            print("stepper \(sender.tag) clicked. Its value \(sender.value)")

        } catch let error as NSError  {
            print("Could not save \(error), \(error.userInfo)")
        } catch {

        }
    }

///////////////////

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
        let task = Tasks[indexPath.row]
        cell.stepper2.tag = indexPath.row

        cell.stepper2.addTarget(self, action: #selector(stepper2(sender: )), for: .valueChanged)
        cell.ggg.text = task.mytext
        cell.stepperV.text  = String(task.stepper)

        return cell
    }

Solution

  • I don't see where you set the UISteppers value. You need something like this in your tableView(_:cellForRowAt:) implementation:

    cell.stepperV.text = String(task.stepper)
    cell.stepper2.value = task.stepper