Execute code on the main UI thread in Swift.

I recently did an example with a UITableView control and I noticed it did not refresh until you force the TableView to scroll.  Then all of a sudden the new items I added to my array would show up.  Some googling led me to this article which explains to use performSelectorOnMainThread in Objective-C like this:

In another article someone showed that you can use some C++ functions to perform this in swift a little nicer like this:

In C# and WPF we use a similar concept called a Dispatcher.  I simplified this a little but and wrote a little Dispatcher function for Swift that makes dispatching code to the main UI thread very clean and simple. Here is the Dispatcher code:

So if you want to solve the problem I had with the UITableView not updating you would simply write this code:

You can download the code here:  Dispatcher.swift

Leave a Reply

Your email address will not be published. Required fields are marked *