Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift alternative to performSelectorOnMainThread

I want to reload my table data inside a block in this method:

import UIKit
import AssetsLibrary

class AlbumsTableViewController: UITableViewController {

    var albums:ALAssetsGroup[] = []

    func loadAlbums(){
        let library = IAAssetsLibraryDefaultInstance

        library.enumerateGroupsWithTypes(ALAssetsGroupType(ALAssetsGroupAll),
            usingBlock: {(group, stop) in
                if group {
                    self.albums.append(group)
                }
                else {
                    dispatch_async(dispatch_get_main_queue(), {

                        self.tableView.reloadData()

                    })
                }
            }, failureBlock: { (error:NSError!) in println("Problem loading albums: \(error)") })

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        loadAlbums()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        //self.navigationItem.rightBarButtonItem = self.editButtonItem
    }

But the else block will not execute. The error I get is:

'performSelectorOnMainThread' is unavailable: 'performSelector' methods are unavailable

So what is the alternative to 'performSelectorOnMainThread' in swift?

UPDATE:

I am now getting an abort error.

like image 985
Amit Erandole Avatar asked Jun 09 '14 18:06

Amit Erandole


2 Answers

This simple C-function:

dispatch_async(dispatch_get_main_queue(), {

        // DO SOMETHING ON THE MAINTHREAD
        self.tableView.reloadData()
        })

What about launching your function with:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {

        loadAlbums()

})

in viewDidLoad()?

like image 129
Ben Avatar answered Oct 25 '22 23:10

Ben


Swift 3

DispatchQueue.main.async(execute:
{
    //Code to execute on main thread
})
like image 5
Tom Howard Avatar answered Oct 25 '22 22:10

Tom Howard