Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moving a function to a background thread in objective c

I have a function that returns a string that takes 15 seconds to compute on an iPhone.

I want to be able to run the function on the background thread so that the main thread can be used for the user interface.

I've heard GCD is a new technology that is good for this, can someone provide some example code in regards to how this would work?

That is to run a generic function on the background thread and return the result to a UI text field.

EDIT:

Thanks Alladinian it works a treat.

However, when I use GCD my function takes 1 second longer to execute on the iphone simulator (I'd guess this'd be about 5 seconds on an iphone (ill have to test it later today to be sure))

Is there any reason why this is? Perhaps the background thread is slower or something?

like image 600
MoKaM Avatar asked Oct 01 '12 09:10

MoKaM


2 Answers

Well that's pretty easy actually with GCD. A typical workflow would be something like this:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul); dispatch_async(queue, ^{     // Perform async operation     // Call your method/function here     // Example:     NSString *result = [anObject calculateSomething];     dispatch_async(dispatch_get_main_queue(), ^{         // Update UI         // Example:         self.myLabel.text = result;     }); }); 

For more on GCD you can take a look into Apple's documentation here

like image 89
Alladinian Avatar answered Oct 19 '22 23:10

Alladinian


Also to add, sometimes you don't need to use GCD, this one is very simple to use :

[self performSelectorInBackground:@selector(someMethod:) withObject:nil]; 
like image 23
Trausti Thor Avatar answered Oct 20 '22 00:10

Trausti Thor