performSelectorOnMainThread:和主队列上的dispatch_async()有什么区别? [英] What's the difference between performSelectorOnMainThread: and dispatch_async() on main queue?

查看:85
本文介绍了performSelectorOnMainThread:和主队列上的dispatch_async()有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在修改线程内的视图时遇到问题.我试图添加一个子视图,但是显示大约需要6秒钟或更长时间.我终于让它工作了,但我不知道它到底是怎么做到的.所以我想知道为什么它起作用,以及以下方法之间的区别是什么?

I was having problems modifying a view inside a thread. I tried to add a subview but it took around 6 or more seconds to display. I finally got it working, but I don't know how exactly. So I was wondering why it worked and what's the difference between the following methods:

  1. 这有效-立即添加了视图:

dispatch_async(dispatch_get_main_queue(), ^{
    //some UI methods ej
    [view addSubview: otherView];
}

  1. 这大约需要6秒钟或更长时间才能显示:

[viewController performSelectorOnMainThread:@selector(methodThatAddsSubview:) withObject:otherView
    waitUntilDone:NO];

  1. NSNotification方法-还花了大约6秒钟才能显示观察者在viewController中,我想修改成对的方法来添加子视图.
  1. NSNotification methods - took also around 6 seconds to display the observer was in the viewController I wanted to modify paired to a method to add a subview.

[[NSNotificationCenter defaultCenter] postNotificationName:
 @"notification-identifier" object:object];

作为参考,在类ACAccountStoreCompletionHandler内部调用了这些变量.

For reference these were called inside this CompletionHandler of the class ACAccountStore.

accountStore requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) {
    if(granted) {
        // my methods were here
    }
}

推荐答案

默认情况下,-performSelectorOnMainThread:withObject:waitUntilDone:仅计划选择器以默认运行循环模式运行.如果运行循环处于另一种模式(例如跟踪模式),则在运行循环切换回默认模式之前它不会运行.您可以使用变体-performSelectorOnMainThread:withObject:waitUntilDone:modes:(通过传递您希望它在其中运行的所有模式)来解决此问题.

By default, -performSelectorOnMainThread:withObject:waitUntilDone: only schedules the selector to run in the default run loop mode. If the run loop is in another mode (e.g. the tracking mode), it won't run until the run loop switches back to the default mode. You can get around this with the variant -performSelectorOnMainThread:withObject:waitUntilDone:modes: (by passing all the modes you want it to run in).

另一方面,一旦主运行循环将控制流返回到事件循环时,dispatch_async(dispatch_get_main_queue(), ^{ ... })将运行该块.它不在乎模式.因此,如果您也不想关心任何模式,则dispatch_async()可能是更好的选择.

On the other hand, dispatch_async(dispatch_get_main_queue(), ^{ ... }) will run the block as soon as the main run loop returns control flow back to the event loop. It doesn't care about modes. So if you don't want to care about modes either, dispatch_async() may be the better way to go.

这篇关于performSelectorOnMainThread:和主队列上的dispatch_async()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆