Warn on calls to UIKit from background threads

前端 未结 3 1495
[愿得一人]
[愿得一人] 2021-01-02 09:58

iOS\'s UIKit is not thread-safe, let us call this fact well known. I know the rule, I\'m careful, but I still get bitten - and every now and then the resulting crash is far

相关标签:
3条回答
  • 2021-01-02 10:08

    I try not to introduce multi threading unless I have tried a single threaded approach first but it depends on the problem you are trying to solve.

    Even when multithreading is the only option I usually avoid long running background operations or operations that that perform several unrelated tasks.

    Just my opinion.

    Edit

    An example of doing work on the main thread whilst displaying a loading spinner:

    MBProgressHUD *hud = [MBProgressHUD customProgressHUDInView:view dim:dim];
    [hud show:NO];
    //Queue it so the ui has time to show the loading screen before the op starts
    NSBlockOperation *blockOp = [NSBlockOperation blockOperationWithBlock:block];
    NSBlockOperation *finOp = [NSBlockOperation blockOperationWithBlock:^{
        [MBProgressHUD hideAllHUDsForView:view animated:NO];
    }];
    [finOp addDependency:blockOp];
    [[NSOperationQueue mainQueue] addOperations:@[blockOp, finOp] waitUntilFinished:NO];
    
    0 讨论(0)
  • 2021-01-02 10:14

    Personally anytime I open the box to a multithreaded approach I start wrapping ALL interface based calls in performSelectorOnMainThread: so that there is never an issue. If we've already made it to the main there this call shouldn't cause any significant slow down, but if its called from a background thread I can rest easy knowing its safe.

    0 讨论(0)
  • 2021-01-02 10:18

    This code (just add to project and compile this file without ARC) causes assertions on UIKit access outside of the main thread: https://gist.github.com/steipete/5664345

    I've just used it to pickup numerous UIKit/main thread issues in some code I've just picked up.

    0 讨论(0)
提交回复
热议问题