Swift 3.0: How to call a method on main thread?

Hi guys, long time no posting on my blog, from now on I’m going to post a lot of useful stuff about Swift 3.0+.

Most of the time when we are building an app we need to make a method call on main thread even if we are not actually on main thread.

The most common case is when we are using tableview and need to refresh its content like this:

self.tableView?.reloadData();

If you run the code above it won’t work properly or it will show an error, because you need to run it in the main thread. To make this code actually work, you need to call it like this:

 

        DispatchQueue.main.async(execute: {() -> Void in

             self.tableView?.reloadData();

        })

DispatchQueue manages the execution of work items. Each work item submitted to a queue is processed on a pool of threads managed by the system.

Basically the code above is calling the class DispatchQueue with the property main, which means you want to call the method inside the main thread, this method won’t return anything.

Acknowledgment

Thanks for reading this post, it is always a pleasure writing for you guys. If you like what you just read and somehow you want to support me, you can become a Patreon . Being my Patreon makes you get my private posts about programming with iOS and Ruby.

If you’d like to know more about me or what I do, you can follow me on Instagram or Twitter .

See you next time!

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s