UITableView doesn’t immediately reload data

awakeFromNib


Here’s a little problem and solution I ran into the other day while using UITableView. I wanted to have a master-detail set up in which the UITableView was segued to after an initial home screen.

The problem occurred whenever I added or deleted something in the UITableView, segued back to the home page and then returned to the table view. Sometimes the table would not update. Going out and back into the view a second time, however, would finally reload my data and show me the changes. Why was my app needing to load the view twice before the table would show any changes?

Logging showed me that something even weirder was going on: Every time I segued into the table view, the viewDidLoad method was being called not once, but twice. So basically, to get my updated data to show, I was actually calling viewDidLoad four times!

I worked through a whole bunch of stackexchange posts related to various problems and solutions with the reloadData method — adding delays, removing it from any edit- or insert- methods and so on, calling it on the main thread — but the problem stubbornly remained.

Then I noticed something else. In my awakeFromNib method, the call to super had somehow got pushed to the end of the method, after a bunch of other set up calls. I’m not sure how it got there, but I did remember seeing a WWDC 2014 Swift video pointing out that one difference between Objective-C and Swift was that calls to super need to be made after doing any initial set up in Swift’s case, but before for Objective-C. Since this was an Obj-C project, what was my call to super doing at the end of the method?

And as if by magic, moving [super awakeFromNib] to the beginning of my awakeFromNib method resulted in viewDidLoad only being called once, and my table view updating correctly.

Though I found quite a few threads with people having a similar problem with UITableView’s needing two calls before updating, I haven’t come across this particular solution to (or cause of) the problem. Hopefully, this post will save someone else a few hours of head scratching!

About philastokes

Independent Software Developer, Technical Writer and Researcher at SentinelOne. Explaining the unexplainable with images, video and text. Scripting anything imaginable in AppleScript, Bash, Python and Swift.

Posted on August 13, 2014, in Cocoa, Objective-C, Swift, Xcode, Xcode 6 and tagged , , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: