iOS 報錯:(子線程中更新UI)This application is modifying the autolayout engine from a background thread after

今天在寫程序的時候,使用Xcode 運行工程時報出下面的錯誤錯信息,我還覺得是什麼呢,很久沒遇到過這樣的錯誤了。
**ProjectName[1512:778965] This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread. This can lead to engine corruption and weird crashes.**
** Stack:(**
** 0   CoreFoundation                      0x00000001843b61d8 <redacted> + 148** ** 1 libobjc.A.dylib 0x0000000182df055c objc_exception_throw + 56** ** 2 CoreFoundation 0x00000001843b6108 <redacted> + 0** ** 3 Foundation 0x0000000184f9dea4 <redacted> + 192** ** 4 Foundation 0x0000000184de53fc <redacted> + 36** ** 5 UIKit 0x000000018ab5c770 <redacted> + 72** ** 6 UIKit 0x000000018a20e1e8 <redacted> + 1140** ** 7 QuartzCore 0x00000001876ce188 <redacted> + 148** ** 8 QuartzCore 0x00000001876c2e64 <redacted> + 292** ** 9 QuartzCore 0x00000001876c2d24 <redacted> + 32** ** 10 QuartzCore 0x000000018763f7ec <redacted> + 252** ** 11 QuartzCore 0x0000000187666c58 <redacted> + 512** ** 12 QuartzCore 0x0000000187667124 <redacted> + 660** ** 13 libsystem_pthread.dylib 0x000000018344afbc <redacted> + 572** ** 14 libsystem_pthread.dylib 0x000000018344ace4 <redacted> + 200** ** 15 libsystem_pthread.dylib 0x000000018344a378 pthread_mutex_lock + 0** ** 16 libsystem_pthread.dylib 0x0000000183449da4 start_wqthread + 4** **)** 

從上面的報錯信息能夠看出,主線程在運行的時候子線程修改了主線程UI的佈局約束,在iOS開發中,全部的有關界面UI的更新操做必須在主線程中完成。這樣的錯誤很容易出如今使用block的時候,由於個人block就是在子線程中進行的,因此回顧了剛纔本身寫的代碼,發現還真是粗心了。
解決的辦法就是把有關UI更新的代碼操做放到主線程中就能夠了。
修改前:app

  [self.healthMgr stepCount:^(double steps, NSError *error) {
            cell.stepsNumberLabel.text = [NSString stringWithFormat:@"%.0f 步數", steps];
    }];
    
    [self.healthMgr distance:^(double distance, NSError *error) {
            cell.distanceLabel.text = [NSString stringWithFormat:@"%.02f 千米", distance];
    }];
    
    [self.healthMgr floorsClimbed:^(double floors, NSError *error) {
            cell.floorsNumberLabel.text = [NSString stringWithFormat:@"%.0f 樓層", floors];
    }];

 

修改後:async

[self.healthMgr stepCount:^(double steps, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            cell.stepsNumberLabel.text = [NSString stringWithFormat:@"%.0f 步數", steps];
        });
    }];
    
    [self.healthMgr distance:^(double distance, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            cell.distanceLabel.text = [NSString stringWithFormat:@"%.02f 千米", distance];
        });
    }];
    
    [self.healthMgr floorsClimbed:^(double floors, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            cell.floorsNumberLabel.text = [NSString stringWithFormat:@"%.0f 樓層", floors];
        });
    }];

 

這時候,你可能會問block是在子線程執行的嗎?
答:不必定。這個得看你執行block的時候,是哪一種線程了,要是在主線程執行block,那麼你的block裏邊的線程就是主線程了。不然就是子線程。佈局

相關文章
相關標籤/搜索