iOS Main Thread Checker-主线程检查器

先放出Apple官方解释地址:主线程检查器

链接地址: https://developer.apple.com/documentation/code_diagnostics/main_thread_checker?language=objc

经过一番苦心研究之后,大概意思说: 应用中有些操作,如更新UI必须在主线程操作实现,否则就会触发此主线程检查器。

如官网例子:

error:

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

right:

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];

在实际开发中,我还碰到过使用 MBProgressHUD 也会触发此主线程检查器,这个其实只是一种Xcode官方提供的检查的方法,有的时候并不会导致多大问题。而且只在 Run时会出现,在开发上线并不会出现。或者只在 Debug 模式下出现,不会在 Release中出现。

但是有的时候会短暂卡死应用,这时候看日志打印旧有相应的错误,当然了 主线程检测也可以关闭。

关闭方法:
Edit Scheme -> Run -> Diagnostics -> Runtime API Checking : Main Thread Checker取消勾选即可
    

但根据最新的Apple-Xcode,iOS 13.0中出现,未在主线程实现某些操作或方法,会导致应用某些崩溃的出现。所以,在Run代码后如果触发主线程检查器,及时查找更改,以避免发生的未知错误。

你可能感兴趣的:(iOS Main Thread Checker-主线程检查器)