我使用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)