Adeel
Adeel

Reputation: 123

How to create an asynchronous while loop in xcode

how can i add this piece of code inside an asynchronous block which keeps on running in the background?

for(int i=0;i<10; i++){
        carRPM = [NSString stringWithFormat:@"%d",i];
        NSLog(@"Car RPM: %@",carRPM);
    }

Upvotes: 0

Views: 1287

Answers (2)

chrissukhram
chrissukhram

Reputation: 2967

You would want to dispatch an asynchronous thread to execute your code from within a closure using the following syntax:

dispatch_queue_t myQueue = dispatch_queue_create("My Queue",NULL);
dispatch_async(myQueue ,^{
    for(int i=0;i<10; i++){
    carRPM = [NSString stringWithFormat:@"%d",i];
    NSLog(@"Car RPM: %@",carRPM);
    }

   dispatch_async(dispatch_get_main_queue(), ^{
    // Update the UI

   });
});

EDIT: Updated my code to be more accurate for running on a separate thread as well as added a block from within the thread to update UI as you update the UI via the main thread.

Upvotes: 2

Popeye
Popeye

Reputation: 12123

You can create a separate thread to run your loop in by using GCD and using dispatch_async().

// Create the new thread that you want to run the loop on.
dispatch_queue_t myLoopQueue = dispatch_queue_create("My Loop Queue", NULL);
dispatch_async(myLoopQueue, ^{
    for(int i=0;i<10; i++) {
        carRPM = [NSString stringWithFormat:@"%d",i];
        NSLog(@"Car RPM: %@",carRPM);
    }
});

I'll assume that you will want to use the value stored within carRPM sooner or later. So it would be wise to know that the final value of carRPM will be lost once the thread is finished. To be able to use the final value of carRPM that has been set within the block you'll need to mark carRPM with the keyword __block, checkout the explanation of this keyword here.

If you just use dispatch_get_main_queue() this will run your loop on the main thread and NOT on a separate thread.

Upvotes: 0

Related Questions