简体   繁体   中英

execution in background and main thread ios

I have a function foo() which is calling a function bar on a background thread foo() {

  [self performSelectorInBackground:@selector(bar:) withObject:nil]; }  bar() { //some initialsations //calling another function bar1();//also in background //after bar1() returns //marking following statement with * [self performSelectorOnMainThread:@selector(stopActivityIndicator:)withObject:nil wailUntilDone:YES]; } 

[self performSelectorInBackground:@selector(bar:) withObject:nil]; } bar() { //some initialsations //calling another function bar1();//also in background //after bar1() returns //marking following statement with * [self performSelectorOnMainThread:@selector(stopActivityIndicator:)withObject:nil wailUntilDone:YES]; }

  [self performSelectorInBackground:@selector(bar:) withObject:nil]; }  bar() { //some initialsations //calling another function bar1();//also in background //after bar1() returns //marking following statement with * [self performSelectorOnMainThread:@selector(stopActivityIndicator:)withObject:nil wailUntilDone:YES]; } 

bar() does some things before calling another function. All that bar() does is in the background. In the meanwhile, I am showing the ActivityIndicator. Once my function inside bar() returns, I am calling a function that will stopActivityIndicator on the MainThread.

Now, I want to do call another function in the MainThread before calling the stopActivityIndicator() How do I do it? Can I put another [self performSelectorOnMainThread:@selector(functionIWantToCall:)withObject:nil wailUntilDone:YES]; before * ?

You can dispatch a block to run on the main thread and put whatever code you need into that block:

[[NSOperationQueue mainQueue] addOperationWithBlock:^ {

   // Code here
   NSLog(@"This is the main thread");

}];

Using your code, that'd become:

bar()
{
    bar1();

    [[NSOperationQueue mainQueue] addOperationWithBlock:^ {
        [stopActivityIndidator];
        [functionIWant];
    }];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM