【问题标题】:what is the difference to call performSelectorOnMainThread() between in viewDidLoad() and in eventmethod()? (ios)在 viewDidLoad() 和 eventmethod() 中调用 performSelectorOnMainThread() 有什么区别? (IOS)
【发布时间】:2012-04-22 09:13:26
【问题描述】:
//viewcontroller.m

-(void)viewdidLoad
{
   self.theOneViewController= [[TheOneViewController alloc]init];
  [contentsView addSubview:self.theOneViewController.view];
}


//theOneViewController

- (void)viewDidLoad
{          .
           .
           .
       //UI WORK
           .
           .
    //LONG WORK  
[self performSelectorOnMainThread:@selector(initAppList) withObject:nil waitUntilDone:NO]; 

}

这段代码,在 LONG WORK 结束之前查看显示 UI WORK。所以我可以有一个线程效果。

//viewcontroller.m

-(void) buttonPressed:(id)sender    -> event method
{
 self.theOneViewController= [[TheOneViewController alloc]init];
 [contentsView addSubview:self.theOneViewController.view];
}

 //theOneViewController
 - (void)viewDidLoad
 {         .
           .
           .
      //UI WORK
           .
           .
  //LONG WORK 
  [self performSelectorOnMainThread:@selector(initAppList) withObject:nil waitUntilDone:NO]; 
 }

在此代码中,在 LONG WORK 结束后查看显示 UI WORK。 所以我不能有线程效果。为什么? 我使用 (performSelectorInBackground:withObject:) 而不是 (performSelectorOnMainThread withObject:waitUntilDone:) 。但这比不使用线程要慢。

我想在事件方法调用中有线程效果。 有什么好办法吗?请帮帮我!

【问题讨论】:

    标签: ios multithreading performselector


    【解决方案1】:

    你的问题不是特别清楚,但我会尝试回答。

    您正在通过viewDidLoadbuttonPressed 方法调用performSelectorOnMainThread:withObject:waitUntilDone:。这样做的问题是所有 UI 处理(viewDidLoad、UI 事件等)都在主线程上完成,这意味着调用 performSelectorOnMainThread 只会在主线程 runloop 上排队该方法。这可能意味着该方法将在调用方法完成后立即运行。

    最终,与直接调用方法相比,这样做并没有真正获得太多收益,因为主线程将花费大约相同的时间来执行任何一种方式。

    调用performSelectorOnBackgroundThread:withObject: 将在单独的线程上运行initAppList 方法,允许主线程继续处理UI。但是,正如您所注意到的,总体上这可能会慢一些,因为创建后台线程会产生开销。

    【讨论】:

      【解决方案2】:

      首先,viewDidLoad 只会在主线程上调用,因此您不必调用 performSelectorOnMainThread:

      其次,如果你打算在后台做一些耗时的工作,那么在任何显式线程之前尝试GCD

      dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_HIGH, 0),^ {
          // long work
      });
      

      【讨论】:

        猜你喜欢
        • 2011-03-26
        • 1970-01-01
        • 2010-10-09
        • 2012-03-09
        • 2019-03-18
        • 2013-09-01
        • 2014-04-08
        • 2017-05-02
        • 1970-01-01
        相关资源
        最近更新 更多