Nick
Nick

Reputation: 85

Should I keep initializing a new ViewController every time or reset the old ViewController?

I have an app where the user has a list of stocks that they follow (so it can vary/change). When the user clicks on a cell in the list, it opens up a StockViewController() that shows the stock data. I've started to worry that initialing a new ViewController every time is bad practice and causing an increase in memory usage over time (Not even entirely sure if that's true).

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if(indexPath.section == 1) {
        let stockVC = StockViewController()
        stockVC.parentView = self
        stockVC.stock = followingStocks[indexPath.row]
        DispatchQueue.main.async {
            self.present(stockVC, animated: true, completion: nil)
        }
    }
}

I have tried attempting to use the same ViewController by reseting the tableview/data inside of it after each use but am having trouble successfully making this a smooth process. Is doing it the above way going to cause issues in my app or should I try to use the same ViewController, below, each time?

class VCManager {

    static var stockVC = StockViewController()

    static func resetStockVC() {
        stockVC.stockData = [StockData]()
        stockVC.tableView.reloadData()
    }
}

Upvotes: 0

Views: 152

Answers (2)

RTasche
RTasche

Reputation: 2644

I agree with Reza. Caching a view controller is uncommon. Creating a new instance of a view controller is really fast und laying out its views depends on the complexity of the view hierarchy.

Creating a new view controller every time you need not only has the advantage of consuming memory only when you need it and as long as you need it but it also removes state handling from it. I.e. you do no longer need to take care of updating your model and that your table view is in sync with the underlying model data aka making sure that your datasource is up to date with the model and tableView.reloadData(). Ideally you'd inject your model array as part of your initializer and store it as a property constant. Using a constant also makes your intent obvious for others that there will be no model changes to worry about.

Upvotes: 0

Reza Takhti
Reza Takhti

Reputation: 80

Initializing a new view controller every time is not only fine, but very common. When you dismiss that view controller, the memory for it is automatically deallocated, so you won't be increasing your memory usage overtime. (With the exception that you have a retain cycle in that view controller that could potentially cause a memory leak, but that's a whole different topic of its own).

Upvotes: 1

Related Questions