So, my friend and I are working on an iPhone app that allows you to bookmark items and then look through a list of them. On the surface, it doesn’t seem to be too big of a deal.
We have one TableView with all the items and another TableView with all the ones we’ve bookmarked. We got together the other day to work on our app and after spending some time on our bookmark it feature we were ready to commit, push and call it a day.
But wait! My friend, having a background in software testing, wouldn’t let me go just yet and insisted on tinkering with the app some more before pushing our most recent changes. Thusly, we encountered the following issue: we could scroll through out list of bookmarked items, select an item and look at its details and choose to remove it from bookmarks, then go back to the list. However, our list looked just like before we removed the bookmark (i.e. the data didn’t get reloaded) and that was an issue.
So, we got to searching online for a solution. We tried calling self.tableView.reloadData() from a variety of places (viewDidLoad, viewDidAppear, viewWillAppear, etc) but none of them seemed to do the trick.
At this juncture I would like to point out I was really starting to hate my friend and his decision to use Embed in Navigation Controller as the way to switch between list/detail. Had we used a simple segue, as we’d done before, our issue would have been resolved a lot quicker. As it was, after a variety of very ingenious places where we tried to stick out self.tableView.reloadData() yielded no results, we turned to Slack.
On Slack, we’ve both subscribed to one of the coolest teams around, iOS Developers (https://ios-developers.io), and I’m not just saying that. Give it a try, you’ll find a lot of people just as enthusiastic about iOS development as you are and who are always ready to help. Here, we were lucky enough to get help from someone who not only solved our problem, but also explained the concept better to us.
- viewDidLoad() is only called the first time your view is created, i.e. the first time you access it. Any subsequent navigations to your view do not call viewDidLoad().
- Consequently, it’s a best practice to only do static actions in your viewDidLoad(), and by static I mean stuff like initializing your view’s name or some controllers within it.
- All data you’d like to list in your view should be created/shown from your viewWillAppear() function. Now, take great care with your variables. If, like us, you use an array to populate your view, in viewWillAppear() you should check if the array is filled or if it’s contents is the same as the last time you accessed your view. If either of those two if false, then you have to repopulate your array, then call self.tableView().reloadData().
And, there you have it, the answer to our question. I needn’t tell you that as soon as we got this to work, I committed and pushed everything before my friend could get the chance to find something else wrong with it.