相关疑难解决方法(0)

在主线程上运行NSURLSession完成处理程序

我使用NSURLSession来获取填充TableView的值.我正在完成处理程序中更新TableView,但是使用[[NSThread currentThread] isMainThread]已经向我显示完成处理程序没有在主线程中运行.由于我只应该从主线程更新UI,我知道这是不正确的.有没有办法从完成处理程序触发主线程上的操作?或者使用NSURLSession以错误的方式去做这个?

NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:@"http://myurl"]
        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            NSError *jsonError = nil;
            NSArray* jsonUsers = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
            if (jsonError) {
                NSLog(@"error is %@", [jsonError localizedDescription]);
                // Handle Error and return
                return;
            }
            self.userArray = jsonUsers;
            [self.userTableView reloadData];
            if ([[NSThread currentThread] isMainThread]){
                NSLog(@"In main thread--completion handler");
            }
            else{
                NSLog(@"Not in main thread--completion handler");
            }
}] resume];
Run Code Online (Sandbox Code Playgroud)

cocoa multithreading ios ios7

24
推荐指数
2
解决办法
3万
查看次数

标签 统计

cocoa ×1

ios ×1

ios7 ×1

multithreading ×1