fis*_*ato 117 iphone cocoa multithreading objective-c xamarin.ios
有没有办法检查当前线程是否是Objective-C中的主线程?
我想做这样的事情.
- (void)someMethod
{
if (IS_THIS_MAIN_THREAD?) {
NSLog(@"ok. this is main thread.");
} else {
NSLog(@"don't call this method from other thread!");
}
}
Run Code Online (Sandbox Code Playgroud)
boh*_*rna 23
如果要在主线程上执行方法,可以:
- (void)someMethod
{
dispatch_block_t block = ^{
// Code for the method goes here
};
if ([NSThread isMainThread])
{
block();
}
else
{
dispatch_async(dispatch_get_main_queue(), block);
}
}
Run Code Online (Sandbox Code Playgroud)
dim*_*mdy 19
在Swift3中
if Thread.isMainThread {
print("Main Thread")
}
Run Code Online (Sandbox Code Playgroud)
Eri*_*ric 12
如果你想知道你是否在主线程上,你可以简单地使用调试器.在您感兴趣的行设置断点,当程序到达时,请调用:
(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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
40869 次 |
| 最近记录: |