Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView reload data in Swift

There's this code of the test project in Objective-C:

@implementation ViewController {
    NSArray *_locations;
}

- (void)viewDidLoad
{
[super viewDidLoad];
JSONLoader *jsonLoader = [[JSONLoader alloc] init];

NSURL *url = [[NSURL alloc]initWithString:@"http://mechnikova.info/api/pic2.php?task=1"]; 

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
    _locations = [jsonLoader locationsFromJSONFile:url];

    [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
});

There's this code of the same test project in Swift:

class ViewController: UITableViewController {
var locations:NSArray=[]

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    var jsonLoader:JSONLoader = JSONLoader()
    var url = NSURL(fileURLWithPath: "http://mechnikova.info/api/pic2.php?task=1")
    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_HIGH, 0), {
        self.locations = jsonLoader.locationsFromJSONFile(url)
        self.tableView.performSelectorOnMainThread(selector:(reloadData), withObject: nil, waitUntilDone: true)
    })
}

I have error - Use of unresolved identifier 'reloadData' in

self.tableView.performSelectorOnMainThread(selector:(reloadData), withObject: nil, waitUntilDone: true)

Help please!

like image 241
Alexey Nakhimov Avatar asked Feb 13 '23 18:02

Alexey Nakhimov


2 Answers

Use:

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_HIGH, 0), {
        self.locations = jsonLoader.locationsFromJSONFile(url)
        dispatch_async(dispatch_get_main_queue(),{
           self.tableView.reloadData()
        })
    })
like image 154
Ben Avatar answered Feb 15 '23 07:02

Ben


for convenience, you can use Costant

let diffQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)
let diffMain = dispatch_get_main_queue()

and then used in a viewDidLoad()

override func viewDidLoad() {
        super.viewDidLoad()
dispatch_async(diffQueue) {
           self.locations = jsonLoader.locationsFromJSONFile(url)
                dispatch_async(self.diffMain){
                    self.tableView.reloadData()
                }
            })
        }
}
like image 26
Beslan Tularov Avatar answered Feb 15 '23 08:02

Beslan Tularov