what is the difference to call performSelectorOnMainThread() between in viewDidLoad() and in eventmethod()? (ios)

StackOverflow https://stackoverflow.com/questions/10266687

Question

//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]; 

}

this code, view display UI WORK before LONG WORK is end.So I can have a thread effect.

//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]; 
 }

In this code, view display UI WORK after LONG WORK is end. So I can't have thread effect. why? And I use (performSelectorInBackground:withObject:) instead of (performSelectorOnMainThread withObject:waitUntilDone:) . but this is slower than not using thread.

I want to have thread effect in event method call. Is there a good way? help me please!

Was it helpful?

Solution

Your question isn't particularly clear but I'll have a go at answering.

You are calling performSelectorOnMainThread:withObject:waitUntilDone: from either your viewDidLoad or buttonPressed methods. The problem with this is that all UI handling (viewDidLoad, UI events etc) is done on the main thread which means that calling performSelectorOnMainThread will just queue the method on the main threads runloop. This probably means that the method will run immediately after the calling method completes.

Ultimately, you aren't really gaining much by doing this over just calling the method directly as the main thread will take about the same amount of time to do either way.

Calling performSelectorOnBackgroundThread:withObject: will run the initAppList method on a separate thread, allowing the main thread to continue dealing with the UI. However, as you note, that will probably be a little bit slower overall as there is the overhead of creating the background thread.

OTHER TIPS

first, viewDidLoad will only be called on main thread so you don't have to call performSelectorOnMainThread:

second, if you plan to do some time-comsumed work on background then try GCD before any explicit threading

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_HIGH, 0),^ {
    // long work
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top