Check whether or not the current thread is the main thread

前端 未结 13 967
北恋
北恋 2020-12-02 11:42

Is there any way to check whether or not the current thread is the main thread in Objective-C?

I want to do something like this.

  - (void)someMethod         


        
相关标签:
13条回答
  • 2020-12-02 12:08

    let isOnMainQueue = (dispatch_queue_get_label(dispatch_get_main_queue()) == dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL))

    check this answer from https://stackoverflow.com/a/34685535/1530581

    0 讨论(0)
  • 2020-12-02 12:11

    UPDATE: seems that is not correct solution, according to queue.h header as mentioned @demosten

    The first thought was brought to me, when I was needed this functionality was the line:

    dispatch_get_main_queue() == dispatch_get_current_queue();
    

    And had looked to the accepted solution:

    [NSThread isMainThread];
    

    mine solution 2.5 times faster.

    PS And yes, I'd checked, it works for all threads

    0 讨论(0)
  • 2020-12-02 12:12

    In Swift3

    if Thread.isMainThread {
        print("Main Thread")
    }
    
    0 讨论(0)
  • 2020-12-02 12:18

    If you want to know whether or not you're on the main thread, you can simply use the debugger. Set a breakpoint at the line you're interested in, and when your program reaches it, call this:

    (lldb) thread info

    This will display information about the thread you're on:

    (lldb) thread info thread #1: tid = 0xe8ad0, 0x00000001083515a0 MyApp`MyApp.ViewController.sliderMoved (sender=0x00007fd221486340, self=0x00007fd22161c1a0)(ObjectiveC.UISlider) -> () + 112 at ViewController.swift:20, queue = 'com.apple.main-thread', stop reason = breakpoint 2.1

    If the value for queue is com.apple.main-thread, then you're on the main thread.

    0 讨论(0)
  • 2020-12-02 12:21

    If you want a method to be executed on the main thread, you can:

    - (void)someMethod
    {
        dispatch_block_t block = ^{
            // Code for the method goes here
        };
    
        if ([NSThread isMainThread])
        {
            block();
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), block);
        }
    }
    
    0 讨论(0)
  • 2020-12-02 12:21
    void ensureOnMainQueue(void (^block)(void)) {
    
        if ([[NSOperationQueue currentQueue] isEqual:[NSOperationQueue mainQueue]]) {
    
            block();
    
        } else {
    
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
    
                block();
    
            }];
    
        }
    
    }
    

    note that i check the operation queue, not the thread, as this is a more safer approach

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