Check whether or not the current thread is the main thread

前端 未结 13 969
北恋
北恋 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:21

    Swift Version


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

    Details

    • Swift 5.1, Xcode 11.3.1

    Solution 1. Detect any queue

    Get current DispatchQueue?

    Solution 2. Detect only main queue

    import Foundation
    
    extension DispatchQueue {
    
        private struct QueueReference { weak var queue: DispatchQueue? }
    
        private static let key: DispatchSpecificKey<QueueReference> = {
            let key = DispatchSpecificKey<QueueReference>()
            let queue = DispatchQueue.main
            queue.setSpecific(key: key, value: QueueReference(queue: queue))
            return key
        }()
    
        static var isRunningOnMainQueue: Bool { getSpecific(key: key)?.queue == .main }
    }
    

    Usage

    if DispatchQueue.isRunningOnMainQueue { ... }
    

    Sample

    func test(queue: DispatchQueue) {
        queue.async {
            print("--------------------------------------------------------")
            print("queue label: \(queue.label)")
            print("is running on main queue: \(DispatchQueue.isRunningOnMainQueue)")
        }
    }
    
    test(queue: DispatchQueue.main)
    sleep(1)
    test(queue: DispatchQueue.global(qos: .background))
    sleep(1)
    test(queue: DispatchQueue.global(qos: .unspecified))
    

    Result (log)

    --------------------------------------------------------
    queue label: com.apple.root.background-qos
    is running on main queue: false
    --------------------------------------------------------
    queue label: com.apple.root.default-qos
    is running on main queue: false
    --------------------------------------------------------
    queue label: com.apple.main-thread
    is running on main queue: true
    
    0 讨论(0)
  • 2020-12-02 12:25

    Two ways. From @rano's answer,

    [[NSThread currentThread] isMainThread] ? NSLog(@"MAIN THREAD") : NSLog(@"NOT MAIN THREAD");
    

    Also,

    [[NSThread mainThread] isEqual:[NSThread currentThread]] ? NSLog(@"MAIN THREAD") : NSLog(@"NOT MAIN THREAD");
    
    0 讨论(0)
  • 2020-12-02 12:25
    Here is a way to detect what the current queue is
    extension DispatchQueue {
        //Label of the current dispatch queue.
        static var currentQueueLabel: String { String(cString: __dispatch_queue_get_label(nil)) }
    
        /// Whether the current queue is a `NSBackgroundActivityScheduler` task.
        static var isCurrentQueueNSBackgroundActivitySchedulerQueue: Bool { currentQueueLabel.hasPrefix("com.apple.xpc.activity.") }
    
        /// Whether the current queue is a `Main` task.
        static var isCurrentQueueMainQueue: Bool { currentQueueLabel.hasPrefix("com.apple.main-thread") }
    }
    
    0 讨论(0)
  • 2020-12-02 12:27

    Have a look at the NSThread API documentation.

    There are methods like

    - (BOOL)isMainThread

    + (BOOL)isMainThread

    and + (NSThread *)mainThread

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

    The following pattern will assure a method is executed on the main thread:

    - (void)yourMethod {
        // make sure this runs on the main thread 
        if (![NSThread isMainThread]) {
            [self performSelectorOnMainThread:_cmd/*@selector(yourMethod)*/
                                   withObject:nil
                                waitUntilDone:YES];
            return;
        }
        // put your code for yourMethod here
    }
    
    0 讨论(0)
提交回复
热议问题