Will Howe
Will Howe

Reputation: 139

How to update TableView data in Swift

I'm trying to reload the data of my TableView, which reloads successfully when the app launches but does not during the run time of the application. I have a view controller I store objects using core data, and then a second view controller in which I load up the same objects.

The viewDidLoad() method:

let fetchRequest: NSFetchRequest<Workout> = Workout.fetchRequest() 
do {
    let workouts = try PersistenceService.context.fetch(fetchRequest)
    self.routines = workouts
    } catch {}
exerciseTableView.reloadData() // Works

The reloadData() function in this method works, as the data is refreshed every time the app starts. I tried to reload the table data using one of the buttons that I have on my second view controller that opens up a drop down menu.

The buttons action method:

@IBAction func selectRoutineButtonPressed(_ sender: Any) {
        DispatchQueue.main.async {
            self.exerciseTableView.reloadData() // Not Working
        }
        if exerciseTableView.isHidden == true {
            animate(toggle: true, togglingTableView: exerciseTableView)
        }
        else {
            animate(toggle: false, togglingTableView: exerciseTableView)
        }
    }

I originally did not have the DispatchQueue line, but after trying to find a solution I added it. However the table data is still not changing when I press the button.

Any advice would be greatly appreciated, thanks.

Upvotes: 0

Views: 295

Answers (1)

Darshan Kunjadiya
Darshan Kunjadiya

Reputation: 908

Try like this

@IBAction func selectRoutineButtonPressed(_ sender: Any) {

let fetchRequest: NSFetchRequest<Workout> = Workout.fetchRequest() 
do {
    let workouts = try PersistenceService.context.fetch(fetchRequest)
    self.routines = workouts
    } catch {}

    DispatchQueue.main.async {
        self.exerciseTableView.reloadData() // Not Working
    }
    if exerciseTableView.isHidden == true {
        animate(toggle: true, togglingTableView: exerciseTableView)
    }
    else {
        animate(toggle: false, togglingTableView: exerciseTableView)
    }
}

Hope this works for you.

Upvotes: 1

Related Questions