in the UIViewController
's viewDidLoad()
there is a method being called for updating a class variable. Once I navigate to another view controller and come back to this one, UITableView
's delegate methods are being called first where that class variable is being used. App is crashing because that variable is being constructed in viewDidLoad()
. How can this issue be fixed? Thank you.
the class variable in question:
var showHideDict = Dictionary<Int, Bool>()
the viewDidLoad()
:
override func viewWillAppear() {
super.viewWillAppear()
makeAPICall()
}
the API calling method:
func makeAPICall() {
// create helper object
let helper = ModelHelper()
helper.createModels(receivedDict: result! as NSDictionary)
// store the showHideDict
for index in 0...(Modelclass.models.count - 1) {
self.showHideDict[index] = true
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
In your UITableViewDelegate
methods I think you'll want to check whether the data in your dictionary is populated as you expect it to be. For instance, this is what I frequently do in my code:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return tableData?.count ?? 0
}
Which is saying: if tableData
is not nil, then return the number of elements in the array. Otherwise return 0
Then in your cellForRowAt
method, just conditionally check whether the data in your showHideDict
is populated as you expect, if not don't force unwrap. Swift enforces safety with optionals... work with it not against it.
Once your API call is completed, all you need to do is do tableView.reloadData()
and the tableview will be constructed with your newly-populated data.