UITableView reloads data in Swift

Here is the test project code 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];
});

Here is the code for 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 an error - Using the unresolved identifier 'reloadData' in

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

Help me please!

+4
source share
3 answers

Using:

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()
        })
    })
+5
source

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 viewDidLoad ()

override func viewDidLoad() {
        super.viewDidLoad()
dispatch_async(diffQueue) {
           self.locations = jsonLoader.locationsFromJSONFile(url)
                dispatch_async(self.diffMain){
                    self.tableView.reloadData()
                }
            })
        }
}
+2
source

Replace your code

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

with this

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

The difference is creating a selector

+1
source

Source: https://habr.com/ru/post/1543989/


All Articles