performSelectorOnMainThread的阻止版本:withObject:waitUntilDone:

Jim*_*Jim 7 concurrency multithreading objective-c event-handling objective-c-blocks

有没有办法可以执行一个块而不是一个对应于这个和类似方法的选择器?

我有观察者可能会收到主线程上没有生成的事件.我想要在主线程上执行操作,如果它主要是面向UI的.现在,我需要编写两个方法来执行此操作,其中一个是事件观察者,第二个是需要在主线程上执行的代码.

如果可以的话,我想将这一切都封装到一个方法中.

Jos*_*ell 13

GCD应该做的诀窍:

dispatch_sync(dispatch_get_main_queue(), ^{
    // Do stuff here
});
Run Code Online (Sandbox Code Playgroud)

或者,dispatch_async如果你正在计划waitUntilDone:NO.该主队列保证要在主线程上运行,所以它是UI操作安全.

  • 很高兴我能帮助你.我有更多的代表比我知道该怎么做,所以不,没关系,谢谢. (2认同)

fsc*_*idl 12

用于阻止多线程操作的优选技术称为Grand Central Dispatch.您可以在维基百科Grand Central Dispatch(GCD)参考中找到一些示例代码

dispatch_async(backgroundQueue, ^{
        //background tasks

        dispatch_async(dispatch_get_main_queue(), ^{
            //tasks on main thread
        });    
});
Run Code Online (Sandbox Code Playgroud)