Answers:
如果要在主线程上执行方法,则可以:
- (void)someMethod
{
dispatch_block_t block = ^{
// Code for the method goes here
};
if ([NSThread isMainThread])
{
block();
}
else
{
dispatch_async(dispatch_get_main_queue(), block);
}
}
NSOperationQueue.mainQueue().addOperationWithBlock { //your work here }
dispatch_sync()
而不是dispatch_async()
示例,则您在注释中提出的要点会更强。
如果您想知道您是否在主线程上,可以只使用调试器。在您感兴趣的行上设置一个断点,并在程序到达该断点时调用此命令:
(lldb) thread info
这将显示有关您所在线程的信息:
(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
如果该值queue
是com.apple.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
}
_cmd
会自动使用将您的摘要粘贴到ʕ•ᴥ•ʔ中的方法
void ensureOnMainQueue(void (^block)(void)) {
if ([[NSOperationQueue currentQueue] isEqual:[NSOperationQueue mainQueue]]) {
block();
} else {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
block();
}];
}
}
请注意,我检查操作队列,而不是线程,因为这是一种更安全的方法
let isOnMainQueue =(dispatch_queue_get_label(dispatch_get_main_queue())== dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL))
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 }
}
if DispatchQueue.isRunningOnMainQueue { ... }
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))
--------------------------------------------------------
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
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") }
}
更新:似乎是不正确的解决方案,根据@demosten提到的queue.h标头
当我需要此功能时,便想到了第一个想法:
dispatch_get_main_queue() == dispatch_get_current_queue();
并查看了可接受的解决方案:
[NSThread isMainThread];
防雷解决方案快2.5倍。
PS是的,我检查过,它适用于所有线程
When dispatch_get_current_queue() is called on the main thread, it may or may not return the same value as dispatch_get_main_queue(). Comparing the two is not a valid way to test whether code is executing on the main thread.