Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous function execution?

in my iOS app I do the following.

viewDidAppear(){

   // Load a spinner in a view on the top
   [DSBezelActivityView newActivityViewForView:self.view]; 
   // Execute code that require 3 seconds
   ...
   // Stop the spinner
   [DSBezelActivityView removeViewAnimated:YES];
}

The problem is that the spinner doesn't appear, because the the cpu is working hard (something similar). It's like that the code betweek the start and stop has precedence on the rendering of the view.

I would love to find a way to show effectively the start of the spinner, without using a timer to delay the code execution.

Thanks

like image 418
Cla Avatar asked Jun 03 '11 09:06

Cla


People also ask

How do asynchronous functions work?

Asynchronous programming is a technique that enables your program to start a potentially long-running task and still be able to be responsive to other events while that task runs, rather than having to wait until that task has finished. Once that task has finished, your program is presented with the result.

What is asynchronous code execution?

Asynchronous – implies that task returns control immediately with a promise to execute a code and notify about result later(e.g. callback, feature).

What are asynchronous functions used for?

Note: The purpose of async / await is to simplify the syntax necessary to consume promise-based APIs. The behavior of async / await is similar to combining generators and promises. Async functions always return a promise.

Do async functions run at the same time?

You can call multiple asynchronous functions without awaiting them. This will execute them in parallel. While doing so, save the returned promises in variables, and await them at some point either individually or using Promise. all() and process the results.


1 Answers

If you have a method like

-(void) showSpinner:(UIView*)view {
    dispatch_async(dispatch_get_main_queue(), ^{
        [DSBezelActivityView newActivityViewForView:view];
    });
}

there are several ways to call it from a different thread. Choose one from the following:

[NSThread detachNewThreadSelector:@selector(showSpinner:) toTarget:self withObject:self.view];
// or 
[self performSelectorInBackground:@selector(showSpinner:) withObject:self.view];
// or 
NSInvocationOperation *invOperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(showSpinner:) object:self.view];
NSOperationQueue *opQueue = [[NSOperationQueue alloc] init];
[opQueue addOperation:invOperation];
// or 
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [self showSpinner:self.view];
});

Alt + click for details.

like image 100
Jano Avatar answered Sep 30 '22 14:09

Jano