Max Chuquimia
Max Chuquimia

Reputation: 7854

Objective-C performSelectorInBackground - where are called methods run?

Simple question: what happens if I do this:

- (void)viewDidLoad
{
    [self performSelectorInBackground:@selector(myBGMethod) withObject:nil];
}

-(void)myBGMethod
{
    [self myOtherMethod];
}

-(void)myOtherMethod
{
    NSLog(@"This is not Inception");
    //some more code here
}

Will the NSLog() and other code in myOtherMethod be run on the main thread or in the background?

Upvotes: 0

Views: 1278

Answers (3)

FluffulousChimp
FluffulousChimp

Reputation: 9185

If you are ever curious about what thread a particular line of code is executing on, you can put a breakpoint on that line and check the Debug Navigator pane in Xcode:

enter image description here

In this case, I put a breakpoint on NSLog(...)

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSLog(@"HI!");
});

and you can see that we're in Thread 2 com.apple.root.default-priority

Upvotes: 1

Cyrille
Cyrille

Reputation: 25144

It'll be run in the background thread.

You can confirm this by calling NSLog inside all your methods. By default, NSLog prints the thread number along the process ID (pid).

Upvotes: 1

mprivat
mprivat

Reputation: 21912

It'll be run in the background. Once you make the call to myBGMethod in another thread, whatever it calls is made on that same thread unless it specifically requests another thread.

As a side note, depending on which version of iOS you want to support, you might want to learn more about Grand Central Dispatch. It makes multithreading a lot simpler.

Upvotes: 1

Related Questions