Main Thread Checker 问题解决

时间:2024-04-10 13:06:34

1. without a return value

https://developer.apple.com/documentation/code_diagnostics/main_thread_checker

NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
dispatch_async(dispatch_get_main_queue(), ^{ // Correct
self.label.text = [NSString stringWithFormat:@"%lu bytes downloaded", data.length];
});
}];
[task resume];

  

let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let data = data {
DispatchQueue.main.async { // Correct
self.label.text = "\(data.count) bytes downloaded"
}
}
}
task.resume()

  

2. with a return value

https://*.com/questions/45832155/how-do-i-refactor-my-code-to-call-appdelegate-on-the-main-thread

static var realDelegate: AppDelegate?;

static var appDelegate: AppDelegate {
if Thread.isMainThread{
return UIApplication.shared.delegate as! AppDelegate;
}
let dg = DispatchGroup();
dg.enter()
DispatchQueue.main.async{
realDelegate = UIApplication.shared.delegate as? AppDelegate;
dg.leave();
}
dg.wait();
return realDelegate!;
}