1

It seems that the function call [self updateUI]; blocked by boo.

Is boo run in another background thread or same as foo as the code below?

How can the [self updateUI]; not block by boo?

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

- (void)foo
{
    [self performSelectorInBackground@selector(boo) withObject:nil];

    //updaate UI in MainThread
    [self updateUI];
}

- (void)boo
{
    //function here take long time to run;
}
daniel
  • 1,010
  • 6
  • 15

2 Answers2

3

In your code seems that you call foo in background and so the UI is updated in the background thread that is not possible because you need to do that in the main thread. In any case, performSelectorInBackground is a little bit old...use the dispatcher in this way:

- (void)MainFunction
{
    [self foo];
}

- (void)foo
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_PRIORITY_DEFAUL, 0ull), ^{
        [self boo];

        dispatch_async(dispatch_get_main_queue(), ^{
            //updaate UI in MainThread
            [self updateUI];
        };
    };
}

- (void)boo
{
    //function here take long time to run;
}

In this case updateUI wait boo, but if you want updateUI before and doesn't matter when boo finish:

- (void)foo
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_PRIORITY_DEFAUL, 0ull), ^{
        [self boo];
    };

    [self updateUI];
}
Matteo Gobbi
  • 17,697
  • 3
  • 27
  • 41
0

performSelectorInBackground performs the selector on a NEW thread. From Apple docs:

This method creates a new thread in your application, putting your application into multithreaded mode if it was not already. The method represented by aSelector must set up the thread environment just as you would for any other new thread in your program.

If you would like to perform both functions on the SAME background thread, you'll have to declare the background thread (also called queue) as a private member of the class (so it will be accessible from both functions) and perform the selector on that queue

Shai
  • 25,159
  • 9
  • 44
  • 67